ios - 由于NSUserDefaultsDidChangeNotification,UI在后台线程上发生了变化

标签 ios uikit nsuserdefaults nsnotificationcenter

我正在调试一个问题,该问题有时会导致我的应用程序崩溃,并在崩溃报告中显示WebTryThreadLock消息。好像该应用程序崩溃了,因为在后台线程上发送和接收了NSUserDefaultsDidChangeNotification。我在收到通知时进行UI更改,并且强烈建议不要在后台线程上进行UI更改。

如果NSUserDefaultsDidChangeNotification有时(如果不是总是)在后台线程上发送,那么处理此问题的最佳方法是什么?类似于以下内容的内容似乎过分,但可能有必要。

[[NSNotificationCenter defaultCenter] 
 addObserver:self
 selector:@selector(userDefaultsDidChange)
 name:NSUserDefaultsDidChangeNotification
 object:nil];

- (void)userDefaultsDidChange {
    [self performSelectorOnMainThread:@selector(updateUIWithNewUserDefaults)
                           withObject:nil
                        waitUntilDone:NO];
}

- (void)updateUIWithNewUserDefaults {
    // Update UI
}

最佳答案

您应该将消息发送到UI线程的调度队列,然后从那里进行UI修改。

像这样:

dispatch_async(dispatch_get_main_queue(), ^{
  // your code here
});

参见Apple's Grand Central Dispatch documentation

-戴夫

关于ios - 由于NSUserDefaultsDidChangeNotification,UI在后台线程上发生了变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5682554/

相关文章:

ios - Xcode 8.2 : UIPageViewControllerDatasource method broken

ios - 为 iPod、iPhone 和 iPad 设置背景图像?

iphone - 继续在 UITableView 的 "bounce area"中交替行颜色

ios - NSUserDefaults.standardUserDefaults().dictionaryForKey() 返回编译错误

objective-c - NSUserDefaults。 setValue 有效,而不是 setBool

ios - 如何打开Acrobat Reader阅读pdf文件?

ios - 为什么 iOS6 中的 UICollectionView 框架比我定义的要小?

iphone - 如何在不指定大小的情况下为整个 iOS 应用程序设置自定义字体

ios - 如何将文本设置为在快速uiTextField中分为两行

iphone - 使用新版本的应用程序更新和更改设置 plist 文件