退出函数后,NSMutable数组不保留数据

我有一个tableview,我试图用数据填充。 我将值分配给函数中的数组。 一切都保存起来,直到它离开searchWithLocation函数。 看着日志,这让我觉得它与订购有关,就像我没有充分填充我的数据一样。 或者也许这不是原因,我真的不知道。

 - (void)viewDidLoad { [super viewDidLoad]; venueName = [[NSMutableArray alloc] init]; [YLPClient authorizeWithAppId:@"sdgsfgfgfg" secret:@"aegsgdgdfs" completionHandler:^ (YLPClient *client, NSError *error) { // Save your newly authorized client self.client = client; [self.client searchWithLocation:@"Chicago" completionHandler:^ (YLPSearch *search, NSError *error) { for (YLPBusiness *business in search.businesses) { [venueName addObject:business.name]; } NSLog(@"I return results: %lu", (unsigned long)[venueName count]); }]; NSLog(@"I return 0: %lu", (unsigned long)[venueName count]); }]; } ... - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSLog(@"number of rows in section: %lu", (unsigned long)[venueName count]); return [venueName count]; } 

日志:

 2017-09-02 14:46:39.708 whatever[67890:8535793] number of rows in section: 0 2017-09-02 14:46:39.714 whatever[67890:8535793] number of rows in section: 0 2017-09-02 14:46:39.715 whatever[67890:8535793] number of rows in section: 0 2017-09-02 14:46:40.448 whatever[67890:8535846] I return 0: 0 2017-09-02 14:46:41.174 whatever[67890:8535846] I return results: 20 

您对asynchronous程序执行有误解。 每个完成处理程序都可以在“调用”执行path已经终止之后执行。 在你的情况下:

 [self.client searchWithLocation:@"Chicago" completionHandler: // This completion handler can be executed after seconds, minutes or even hours. ^(YLPSearch *search, NSError *error) { NSLog( @"As times go by – sometime in the future" ); for (YLPBusiness *business in search.businesses) { [venueName addObject:business.name]; } NSLog(@"I return results: %lu", (unsigned long)[venueName count]); }]; // This path is executed immediately. esp. likely before the cmpletion handler is executed NSLog( @"It is now or never" ); NSLog(@"I return 0: %lu", (unsigned long)[venueName count]); 

把代码移到里面的完成处理器后面。