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

时间:2011-11-07 01:28:59

标签: iphone ios uiactivityindicatorview ui-thread performselector

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

背景

  • 我正在尝试根据How to add a UIActivityIndicator to a splash screen in a iphone application?
  • 的概念设置加载指标
  • 打算在AppDelete中使用“performSelectorInBackground”来加载模型数据
  • 因此我需要在RootViewController中以某种方式告知数据何时在后台完成加载,以便它可以(a)用数据更新tableview并(b)删除任何活动指示符
  • 我假设在这里做的事情如下:
    • 在App Delegate中将didFinishLaunchingWithOptions传递给模型数据加载到后台
    • AppDelegate加载RootViewController并立即设置活动指示器
    • 一旦数据在后台加载,它就会以某种方式将这个指示回RootViewController(这个问题的原因)它已经完成了
    • 第二个问题可能也就是后台任务确实完成了它的完成,RootviewController如何在尝试禁用活动指示符之前检查UI是否设置了(带有活动指示符等)

2 个答案:

答案 0 :(得分:3)

您可以使用-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]];
}

答案 1 :(得分:1)

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

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

然后在RootViewController中实现-(void)backgroundLoadingDidFinish:(id)sender。如果需要,您可以使用上述方法(withObject:部分)传回数据。