我尝试使用网址从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.如何解决此问题。
提前致谢!
答案 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
}
再次阅读!!问候