iOS – prepareForSegue不等待completionBlock完成

我喜欢什么:等到数据下载完成,然后打开TableView并显示data

我有什么:prepareForSegue被称为TableView立即打开,无需等待data下载,虽然我有一个completionBlock (这可能不会正确实现我猜)。

注意:当我回去并再次打开TableView时,我看到data

 - (void)fetchEntries { void (^completionBlock) (NSArray *array, NSError *err) = ^(NSArray *array, NSError *err) { if (!err) { self.articlesArray = [NSArray array]; self.articlesArray = array; } }; [[Store sharedStore] fetchArticlesWithCompletion:completionBlock]; } -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { [self fetchEntries]; if ([[segue identifier] isEqualToString:@"ShowArticles"]) { TableVC *tbc = segue.destinationViewController; tbc.articlesArrayInTableVC = self.articlesArray; } } 

Store.m

 - (void)fetchArticlesWithCompletion:(void (^) (NSArray *channelObjectFromStore, NSError *errFromStore))blockFromStore { NSString *requestString = [API getLatestArticles]; NSURL *url = [NSURL URLWithString:requestString]; NSURLRequest *req = [NSURLRequest requestWithURL:url]; Connection *connection = [[Connection alloc] initWithRequest:req]; [connection setCompletionBlockInConnection:blockFromStore]; [connection start]; } 

在执行一个seque之前,你应该加载你的数据。

 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // show loading indicator __weak typeof(self) weakSelf = self; [[Store sharedStore] fetchArticlesWithCompletion:^(NSArray *array, NSError *err) { [weakSelf performSegueWithIdentifier:@"ShowArticles" sender:weakSelf]; // hide loading indicator }]; } -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // do whatever } 

虽然在我看来,立即显示下一个视图控制器响应用户交互更好。 你有没有考虑在下一个视图控制器中加载你的数据,而不是在你真正想要转换之前等待它?

我仍然build议乔里斯的答案比这个更多,但从理论上讲,你可以做一些像下面这样的东西:

 - (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender { if ([identifier isEqualToString:@"segueIdentifier"] && !_didFinishExecutingBlock) { [self methodWithCompletionBlock:^{ _didFinishExecutingBlock = YES; [self.navigationController performSegueWithIdentifier:identifier sender:self]; }]; return false; } else return true; } 

因为你正在使用一个块,并且一旦声明完成就执行,所以不会等待,解决方法是删除块

 - (void)fetchEntries { if (!err) { self.articlesArray = [NSArray array]; self.articlesArray = array; } [[Store sharedStore] fetchArticlesWithCompletion:completionBlock]; } -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { [self fetchEntries]; if ([[segue identifier] isEqualToString:@"ShowArticles"]) { TableVC *tbc = segue.destinationViewController; tbc.articlesArrayInTableVC = self.articlesArray; } }