无法从iOS中的JSON读取数据

时间:2014-07-29 04:45:02

标签: ios objective-c json

我尝试使用网址从JSON获取一些数据并将其放入NSMuttableArray。我做了以下代码。

-(void)loadJSONData{
   _lawyerObjects = [[NSMutableArray alloc] init];
    dispatch_async(queue_data, ^{
       NSData *jsonSource = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
       id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonSource options:NSJSONReadingMutableContainers error:nil];
       NSArray *dataDic = [jsonObjects objectForKey:@"data"];
       for (NSDictionary *lawyersDic in dataDic) {

           [_lawyerObjects addObject:[[[Lawyer alloc] init] initFromDictionary:lawyersDic]];
       }
       NSLog(@"%d", dataDic.count);
   });
   NSLog(@"%d", _lawyerObjects.count);
}

在此代码中,dataDic.count返回60,但_lawyersObject返回0.如何解决此问题。

提前致谢!

1 个答案:

答案 0 :(得分:1)

因为这是一个异步函数:

-(void)loadJSONData{
   _lawyerObjects = [[NSMutableArray alloc] init];
    dispatch_async(queue_data, ^{
       NSData *jsonSource = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
       id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonSource options:NSJSONReadingMutableContainers error:nil];
       NSArray *dataDic = [jsonObjects objectForKey:@"data"];
       for (NSDictionary *lawyersDic in dataDic) {

           [_lawyerObjects addObject:[[[Lawyer alloc] init] initFromDictionary:lawyersDic]];
       }
      NSLog(@"%d", _lawyerObjects.count); // data finish load _lawyerObjects.count= 60 
       NSLog(@"%d", dataDic.count); // dataDic.count = 60
   });
   NSLog(@"%d", _lawyerObjects.count); // data couldn't load yet _lawyerObjects.count= 0 
}

再次阅读!!问候