Ios 填充NSArray Json数据

Ios 填充NSArray Json数据,ios,objective-c,json,nsmutabledictionary,Ios,Objective C,Json,Nsmutabledictionary,我有这段代码,需要获取键值nombre并填充一个NSArray*数组,但不起作用 NSURL *urlPaises = [NSURL URLWithString:@"http://tr.com.mx/prb2/buscarPais.php"]; NSData *dataPaises = [NSData dataWithContentsOfURL:urlPaises]; NSArray *array; NSMutableDictionary *jsonPaises; N

我有这段代码,需要获取键值nombre并填充一个NSArray*数组,但不起作用

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;
                }
            );
        }

jsonPaises
是一个数组。数组具有索引
0,1,2
而不是键
“apple”、“foo”、“bar”
。向数组请求键的值永远不会起作用。你有一系列字典。 如果要为原始数组中的每个字典创建一个值为“nombre”的新数组,请尝试以下操作:

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
    }
}

看起来您需要使用
valueForKeyPath

[jsonPaises valueForKeyPath:@"praises.nombre"]

应该返回一个
nombre的数组

您需要更具体一点,键@“nombre”的值是作为单个名称出现还是作为名称数组出现?我猜这是一个名称数组,然后尝试:

for (NSString *name in [jsonPaises objectForKey:@"nombre"]) {
      NSLog("%@", name);
}
如果键@“nombre”的值为单个字符串,则将其添加到数组中,如下所示:

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

啊,很多问题。首先,您正在通过覆盖分配的
NSMutableArray
指针泄漏内存。内存管理不是这样工作的。其次,您可以清楚地看到对象是一个数组,因此它不会响应
objectForKey:
。如果你不能推断出你需要一个循环来解决这个问题,那么在尝试深入研究iOS开发之前,你应该学习更多关于算法、数据结构和编程的知识。(分步学习-帮你自己一个忙。)@H2CO3我想他是在尝试访问字典,并将其结果解析为数组。我很确定他可以使用
valueForKeyPath
,而不需要循环——尽管我可能误解了他的问题。@OliverAtkinson嗯,也许是的。不过,不知道此问题的解决方案表明缺少一些基础知识。感谢您,此操作非常有效=)[array addObject:[jsonPaises valueForKeyPath:@“paises.nombre”];