how to indicate to main UI thread when background task has completed? (performSelectorInBackground)

自古美人都是妖i 提交于 2019-12-04 18:44:40

You can call back into the main thread from your background selector using -performSelectorOnMainThread:withObject:waithUntilDone: like so:

- (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]];
}

Update: an even safer way to do this would be to check in -finishedLoadingModel to make sure you're running on the main thread:

- (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]];
}

Once you're finished loading in the background, call the following from your background thread:

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

And then implement -(void)backgroundLoadingDidFinish:(id)sender in your RootViewController. If you need to, you can pass data back in the above method (the withObject: part).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!