我喜欢什么:等到数据下载完成后再打开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];
}
答案 0 :(得分:2)
您应该在执行隔离之前加载数据。
- (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
}
虽然在我看来,为了响应用户交互,立即显示下一个视图控制器要好得多。您是否考虑过在下一个视图控制器中加载数据,而不是在实际想要转换之前等待它?
答案 1 :(得分:1)
我仍然建议Joris的答案不止于此,但从理论上讲,你可以做一些时髦的事情:
- (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;
}
答案 2 :(得分:0)
它不会等待,因为你正在使用一个块,并且在声明完成后立即执行,解决方案是删除块
- (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;
}
}