ios - 方法不会将接收到的 JSON 对象保存到数组中

标签 ios objective-c json

我有以下从 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;
}

最佳答案

dataTask 是一个异步任务。所以完成 block 在响应到来后命中。但在完成 block 命中之前,您将返回 array。这不是正确的方法。尝试在完成 block 内传递数组(我不是说在完成 block 内返回)。

关于ios - 方法不会将接收到的 JSON 对象保存到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25815212/

相关文章:

python - 在定义的时间后退出 LLDB session

iphone - 您可以跟踪 ASIFormDataRequest 的下载进度吗?

iphone - 在 UITextView 上滚动内部阴影

javascript - 如何合并多个 JSON 对象中的子对象?

mysql - Laravel MySQL JSON LIKE 查询

ios - 为什么使用 Swift 在 View 上执行某些操作时顶部导航栏会消失?

ios - Xamarin.iOS UIPopoverPresentationController 异常

ios - 是否可以在显示本地通知之前触发 api 调用?

iphone - Google Maps iOS SDK 集成不加载 map

java - 获取 org.json.JSONEXCEPTION : Unteterminated object at character when decoding token