繁体   English   中英

在后台运行代码后如何更新主线程上的数据?

[英]How to update data on the main thread after running code in the background?

我有用于处理3个不同数据请求的dispatch_queue代码。 然后,我在主线程上更新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);

这是苹果文件说的:

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

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

dispatch_async(dispatch_get_main_queue(), ^{
    [self.tableView reloadData];
    // Your UI update code here
});

对于Swift3:

DispatchQueue.main.async{
   self.tableView.reloadData()
   // any UI related code 
   self.label.text = "Title"
   self.collectionView.reloadData()
   }

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

[self performSelectorOnMainThread:@selector(doUIStuffOnMainThread:)
                       withObject:self.tableView.data 
                    waitUntilDone:YES];
[your_tableview performSelectorOnMainThread:@selector(reloadData)
                                     withObject:nil
                                  waitUntilDone:YES];

尝试添加一个主队列操作,如下所示:

[[NSOperationQueue mainQueue] addOperationWithBlock:^{
    [self.tableView reloadData];
}];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM