简体   繁体   中英

Cannot invoke code on the main thread from the background thread in iOS6

When saving a managed object context on a background thread I am listening to the NSManagedObjectContextDidSaveNotification and trying to merge it on the main thread.

However when I try to forward the request to the main thread, none of the code is executed neither using

[self performSelectorOnMainThread:@selector(executeThisCode:) withObject:saveNotification waitUntilDone:NO]; 

nor with

dispatch_async(dispatch_get_main_queue(), ^{
    ...execute this code
});

Strangely, it all works fine with iOS 5.1 and iOS 5.0, but not with iOS 6. Any ideas?

Do you first check whether you are already in the main thread? This would be expecially relevant if executeThisCode is the selector for the method you are currently executing when calling performSelectorOnMainThread . Something like this:

- (void) executeThisCode: (NSNotification*) notification{
    if (![NSThread isMainThread]) {
       [self performSelectorOnMainThread:@selector(executeThisCode:) 
                                 withObject:notification 
                              waitUntilDone:YES];
       return;
    }

    // merge logic goes here and executes on the main thread
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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