后台任务完成后如何向主UI线程指示? (performSelectorInBackground)

当后台任务完成后,如何在iPhone应用程序IOS程序中获取主UI线程的指示?

背景

  • 我正在尝试按照如何将UIActivityIndi​​cator添加到iphone应用程序中的启动画面的概念设置加载指示器?
  • 在AppDelete中使用“performSelectorInBackground”来加载模型数据
  • 因此,我需要在RootViewController中以某种方式告知数据何时在后台完成加载,以便它可以(a)用数据更新tableview并(b)删除任何活动指示符
  • 我假设在这里做的事情如下:
    • 在App Delegate中,didFinishLaunchingWithOptions将模型数据加载到后台
    • AppDelegate加载RootViewController并立即设置活动指示器
    • 一旦数据在后台加载,它必须以某种方式指示回RootViewController(这个问题的原因)它已经完成了
    • 第二个问题可能也就是后台任务确实完成了它的完成,RootviewController如何在尝试禁用活动指示符之前检查UI是否设置了(带有活动指示符等)

您可以使用-performSelectorOnMainThread:withObject:waithUntilDone:从后台选择器-performSelectorOnMainThread:withObject:waithUntilDone:主线程-performSelectorOnMainThread:withObject:waithUntilDone:如下所示:

 - (void)loadModel { // Load the model in the background Model *aModel = /* load from some source */; [self setModel:aModel]; [self performSelectorOnMainThread:@selector(finishedLoadingModel) withObject:nil waitUntilDone:YES]; } - (void)finishedLoadingModel { // Notify your view controller that the model has been loaded [[self controller] modelLoaded:[self model]]; } 

更新 :更安全的方法是检查-finishedLoadingModel以确保您在主线程上运行:

 - (void)finishedLoadingModel { if (![NSThread isMainThread]) { [self performSelectorOnMainThread:_cmd withObject:nil waitUntilDone:YES]; } // Notify your view controller that the model has been loaded [[self controller] modelLoaded:[self model]]; } 

在后台加载完成后,从后台线程调用以下内容:

 [self performSelectorOnMainThread:@selector(backgroundLoadingDidFinish:) withObject:nil waitUntilDone:NO]; 

然后在RootViewController中实现-(void)backgroundLoadingDidFinish:(id)sender 。 如果需要,可以在上面的方法( withObject: part)中传回数据。