我有以下方法从API接收JSON数据。该方法接收正确数量的对象,正确识别属性(offer_title),但不将接收/创建的对象保存到“数组”。
如果我检查“数组”中的项目数:
2014-09-12 20:57:47.439 stadtklick[1648:514103] the array with offers has: 0 items
2014-09-12 20:57:50.516 stadtklick[1648:514119] received 4 items
2014-09-12 20:57:50.517 stadtklick[1648:514119] Loaded offer: hhh
2014-09-12 20:57:50.518 stadtklick[1648:514119] Loaded offer: ii
2014-09-12 20:57:50.518 stadtklick[1648:514119] Loaded offer: uu
2014-09-12 20:57:50.519 stadtklick[1648:514119] Loaded offer: eeeeEE
为什么最后一个方法array.count在收到所有对象之前就开始了?
- (NSMutableArray *)defaultPeople {
NSMutableArray *array = [[NSMutableArray alloc] init];
NSString* urlStr = [kBaseURL stringByAppendingPathComponent:kLocations];
NSLog(@"URL: %@",urlStr);
NSURL* url = [NSURL URLWithString:urlStr];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"GET";
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession* session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil) {
[self.offers removeAllObjects];
NSArray* responseArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(@"received %lu items", (unsigned long)responseArray.count);
for (NSDictionary* item in responseArray) {
Offer* offer = [[Offer alloc] initWithDictionary:item];
[array addObject:offer];
NSLog(@"Loaded offer: %@",offer.offer_title);
}
}
}];
[dataTask resume];
NSLog(@"the array with offers has: %lu items", (unsigned long)array.count);
return array;
}
答案 0 :(得分:2)
dataTask
是一个异步任务。因此,在响应到来之后,完成块会命中。但在完成阻止命中之前,您将返回array
。这不是正确的方法。尝试在完成块内传递array
(我不是说在完成块内返回)。