iOS:如何从一系列字典中获取名称列表?

时间:2015-05-25 14:43:16

标签: ios json parsing server

我目前正在尝试从服务器读取文件中的Object:

 NSURLSession *session = [NSURLSession sharedSession];
NSString *string = @"http://myfile.php";
//NSLog(string); //CHECK

[[session dataTaskWithURL:[NSURL URLWithString:string]
       completionHandler : ^(NSData *data,
                             NSURLResponse *response,
                             NSError *error) {
           if (data.length > 0 && error == nil) {
               NSError *jsonvar;
               NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonvar];
               NSLog(@"%@", greeting);

               dispatch_sync(dispatch_get_main_queue(), ^{
                   NSDictionary *main = [greeting objectForKey:@"array"];
                   //self.beaconMajor.text = [NSString stringWithFormat:@"%@", [main objectForKey:@"name"]];

               });
           }
       }] resume];

}

这是我在执行NSLog时得到的响应:

array =     (
            {
        endDate = "0000-00-00";
        id = 3;
        name = ruben;
        startDate = "0000-00-00";
    },
            {
        endDate = "0000-00-00";
        id = 4;
        name = "hallo mama";
        startDate = "0000-00-00";
    },
            {
        endDate = "0000-00-00";
        id = 5;
        name = heyoo;
        startDate = "0000-00-00";
    },
            {
        endDate = "0000-00-00";
        id = 6;
        name = "Gerard Depardieu";
        startDate = "0000-00-00";
    }
);

任何人都可以帮我解释如何读出这个数组的“名称”吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以手动执行此操作:

NSArray *main = [greeting objectForKey:@"array"];
for (NSDictionary *dict in main) {
    NSLog(@"name=%@", dict[@"name"]);
}

或者您可以使用KVC从数组中的字典中获取所有名称:

NSArray *main = [greeting objectForKey:@"array"];
NSArray *names = [main valueForKey:@"name"];

(在数组上使用valueForKey时,它会在每个包含的对象上调用valueForKey