简体   繁体   English

无法从iOS6中的后台线程在主线程上调用代码

[英]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. 当在后台线程上保存托管对象上下文时,我在听NSManagedObjectContextDidSaveNotification并尝试在主线程上合并它。

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? 奇怪的是,这一切都适用于iOS 5.1和iOS 5.0,但不适用于iOS6。有什么想法吗?

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 . 如果executeThisCode是您在调用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
}

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

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