2013-10-19 137 views
2

我有這樣的代碼,並需要獲得鍵值農佈雷和填充的NSArray *數組,但無法工作填充NSArray的JSON數據

NSURL *urlPaises = [NSURL URLWithString:@"http://tr.com.mx/prb2/buscarPais.php"]; 
NSData *dataPaises = [NSData dataWithContentsOfURL:urlPaises]; 

    NSArray *array; 

    NSMutableDictionary *jsonPaises; 
    NSError *error; 

    array = [[NSArray alloc]init]; 


     jsonPaises = [NSJSONSerialization JSONObjectWithData:dataPaises options:kNilOptions error:&error]; 

     array = [jsonPaises objectForKey: @"nombre"]; 


     Printing description of self->jsonPaises: 
     { 
      paises =  (
         { 
        id = 49; 
        nombre = Alemania; 
       }, 
         { 
        id = 54; 
        nombre = Argentina; 
       }, 

         { 
        id = 44; 
        nombre = Inglaterra; 
       }, 

         { 
        id = 598; 
        nombre = Uruguay; 
       }, 
         { 
        id = 58; 
        nombre = Venezuela; 
       } 
      ); 
     } 
+0

噢,很多問題。首先,你通過覆蓋分配的'NSMutableArray'指針來泄漏內存。這不是內存管理的工作方式。其次,你可以清楚地看到對象是一個數組,所以它不會響應'objectForKey:'。如果你無法推斷自己需要循環來解決這個問題,那麼在嘗試深入iOS開發之前,你應該多學習一些關於算法,數據結構和編程的知識。 (在小步驟中學習 - 爲自己做個忙。) – 2013-10-19 16:11:11

+0

@ H2CO3我想他正試圖訪問字典並將其結果解析爲數組。我很確定他可以使用'valueForKeyPath'而不需要循環 - 儘管我可能誤解了他的問題。 –

+0

@OliverAtkinson嗯,也許是的。但是,不知道這個問題的解決方案表明,缺少一些基礎知識。 – 2013-10-19 16:35:11

回答

3

看起來你需要使用valueForKeyPath

[jsonPaises valueForKeyPath:@"praises.nombre"] 

應該返回一個數組nombres

+0

感謝這個完美的作品=) [數組addObject:[jsonPaises valueForKeyPath:@「paises.nombre」]]; – Fabio

0

jsonPaises是一個數組。數組有索引0,1,2不是鍵"apple","foo","bar"。詢問一個數組的值不能工作。你有一系列字典。 如果你想要的是用鑰匙「農佈雷」爲每一個字典的值的新數組,你原來的數組,那麼試試這個:

NSMutableArray * newArray = [[NSMutableArray alloc]init]; //create the new array 
for (NSDictionary * dict in array) { //for each dictionary in the first array 
    id object = dict[@"nombre"]; //get the object stored in the key 
    if(object) { //check that the key/value was actually in the dict 
     [newArray addObject:object]; //add the object to the new Array 
    } 
} 
0

你需要更具體一點是key @「nombre」作爲單個名稱來使用,還是一個名稱數組?我想這是名稱的數組,然後嘗試:

for (NSString *name in [jsonPaises objectForKey:@"nombre"]) { 
     NSLog("%@", name); 
} 

如果key @「農佈雷」的值是一個字符串,那麼你將它添加到數組:

[array addObject:[jsonPaises objectForKey: @"nombre"]];