5

我有这段dispatch_queue代码用于发出 3 个不同的数据请求。然后我tableView在主线程上更新。我还能在主线程中放什么?我正在使用它[self requestExtendedData];从 Web 服务下载数据,然后将其解析并设置为 UILabels 等...

我的问题是:如果我[self requestExtendedData];在后台线程中运行,如何在主线程中使用此数据中的内容更新 UILabel?我应该把其他所有东西都放在主线程区域吗?所有的 UIView、UILabels 和 UIButton 对象等...

谢谢您的帮助

dispatch_queue_t jsonParsingQueue = dispatch_queue_create("jsonParsingQueue", NULL);

// execute a task on that queue asynchronously
dispatch_async(jsonParsingQueue, ^{

    [self requestUserData]; // request user comments data
    [self requestExtendedData]; // request extended listing info data
    [self requestPhotoData]; // request photo data


    // once this is done, if you need to you can call
    // some code on a main thread (delegates, notifications, UI updates...)
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];


    });
});

// release the dispatch queue
dispatch_release(jsonParsingQueue);
4

5 回答 5

2

这是苹果文件所说的:

注意:在大多数情况下,UIKit 类只能在应用程序的主线程中使用。对于从 UIResponder 派生的类或涉及以任何方式操作应用程序的用户界面的类尤其如此。

这意味着您应该将所有UIView,UILabelsUIButtonobjects 代码放在主线程中,如下所示:

dispatch_async(dispatch_get_main_queue(), ^{
    [self.tableView reloadData];
    // Your UI update code here
});
于 2013-08-10T01:03:05.317 回答
1

对于 Swift3 :

DispatchQueue.main.async{
   self.tableView.reloadData()
   // any UI related code 
   self.label.text = "Title"
   self.collectionView.reloadData()
   }
于 2017-09-05T14:21:00.237 回答
0

在你的 dispatch_async 之后尝试这样的事情

[self performSelectorOnMainThread:@selector(doUIStuffOnMainThread:)
                       withObject:self.tableView.data 
                    waitUntilDone:YES];
于 2013-08-09T22:17:31.600 回答
0
[your_tableview performSelectorOnMainThread:@selector(reloadData)
                                     withObject:nil
                                  waitUntilDone:YES];
于 2013-08-10T07:02:08.363 回答
0

尝试像这样添加一个主队列操作:

[[NSOperationQueue mainQueue] addOperationWithBlock:^{
    [self.tableView reloadData];
}];
于 2018-04-20T10:35:32.600 回答