有关使用调度队列同步主线程的问题



预取数据并在uitableview上显示时遇到问题。所以基本上我想阻止主 UI 线程,以便我可以从 web 获取数据。我正在使用串行调度队列进行同步。此外,调度队列块正在执行另一个从 Web 获取数据的块。执行代码是在viewdidload中编写的:

dispatch_queue_t queue= dispatch_queue_create("myQueue", NULL);

CMStore *store = [CMStore defaultStore];
// Begin to fetch all of the items
dispatch_async(queue, ^{
[store allObjectsOfClass:[Inventory class]
       additionalOptions:nil
                callback:^(CMObjectFetchResponse *response) {
                    //block execution to fetch data
                }];
});
dispatch_async(queue, ^{
//load data on local data structure

    [self.tableView reloadData];
});

切勿在主线程/队列以外的任何地方执行任何与 UI 相关的代码。

始终在主线程/队列上执行每个与 UI 相关的代码(如UITableView上的reloadData)。在您的示例中,我想您还应该仅在获取数据时才重新加载表视图,因此在完成块中,而不是在调用回调之前。

// Begin to fetch all of the items
dispatch_async(queue, ^{
   [store allObjectsOfClass:[Inventory class]
       additionalOptions:nil
                callback:^(CMObjectFetchResponse *response) {
                // block execution to fetch data
                ...
                // load data on local data structure
                ...
                // Ask the main queue to reload the tableView
                dispatch_async(dispatch_get_main_queue(), ^{
                    // Alsways perform such code on the main queue/thread
                    [self.tableView reloadData];
                });
    }];
});

最新更新