确保已完成适用于 iOS 的异步任务



我有一个UITableView和一个刷新按钮,以便从服务器获取新数据(如果有的话)。

[self startUpdates]; // animations
[[User myUser] getDataFromServer]; //async
[[User myUser] refreshElements:[[[UpdateContext alloc] initWithContext:data_ with:self with:@selector(endUpdates)] autorelease]];
[self.tableView reloadData];

上面的代码不能很好地工作,因为getDataFromServer是一个异步方法,当服务器返回新数据(响应)时完成。我想 100% 确定只有在 getDataFromServer 得到响应时才执行刷新元素

问题是:这样做的正确方法是什么。我希望第 3 行在且仅当第 2 行从服务器获得响应时执行。有什么想法吗?

最简单的方法是更改 getDataFromServer 方法以接受一个块,该块将包含数据来自服务器后需要执行的代码。您应该确保块将在主线程中执行。下面是一个示例:

更改的方法:

- (void)getDataFromServer:(void (^)(NSError * connectionError, NSDictionary *returnData))completionHandler{
    //perform server request
    //...
    //
    NSDictionary * data; //the data from the server
    NSError * connectionError; //possible error
    completionHandler(connectionError, data);
}

以及如何用块调用新方法:

[self getDataFromServer:^(NSError *connectionError, NSDictionary *returnData) {
    if (connectionError) {
        //there was an Error
    }else{
        //execute on main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            [[User myUser] refreshElements:[[[UpdateContext alloc] initWithContext:data_ with:self with:@selector(endUpdates)] autorelease]];
            [self.tableView reloadData];
        });
    }
}];

最新更新