2

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

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

3 回答 3

3

看起来你需要使用valueForKeyPath

[jsonPaises valueForKeyPath:@"praises.nombre"]

应该返回一个数组nombres

于 2013-10-19T16:12:52.080 回答
0

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
    }
}
于 2013-10-19T16:12:43.067 回答
0

您需要更具体地说明键 @"nombre" 的值是单个名称还是名称数组?我猜这是一个名称数组,然后尝试:

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

如果键 @"nombre" 的值是单个字符串,则将其添加到数组中:

[array addObject:[jsonPaises objectForKey: @"nombre"]];
于 2013-10-19T16:12:58.447 回答