2014-09-12 57 views
0

我有以下方法從API接收JSON數據。該方法接收正確數量的對象,正確識別屬性(offer_title),但不會將接收/創建的對象保存到「數組」中。方法不會將接收到的JSON對象保存到數組中

如果我入住「陣列」的項目數:

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; 
} 

回答

2

dataTask是一個異步任務。所以完成塊在響應到來之後命中。但在完成塊命中之前,您將返回array。這不是正確的做法。嘗試在完成塊內通過array(我不是說在完成塊內部返回)。