由于NSUserDefaultsDidChangeNotification,后台线程的UI更改 [英] UI changes on background thread due to NSUserDefaultsDidChangeNotification
问题描述
我正在调试一个问题,偶尔会导致我的应用程序崩溃,并在崩溃报告中显示 WebTryThreadLock
消息。看起来应用程序崩溃了,因为 NSUserDefaultsDidChangeNotification
正在后台线程上发送和接收。我在收到通知时进行了UI更改,并了解强烈建议在后台线程上进行UI更改。
I am debugging an issue that occasionally causes my app to crash with a WebTryThreadLock
message in the crash report. It looks like the app is crashing because the NSUserDefaultsDidChangeNotification
is being sent and received on a background thread. I make UI changes when the notification is received and understand that making UI changes on a background thread is highly advised against.
如果 NSUserDefaultsDidChangeNotification
有时(如果不是总是)在后台线程上发送,处理这个问题的最佳方法是什么?类似以下内容似乎过多但可能是必要的。
If NSUserDefaultsDidChangeNotification
is sometimes (if not always) sent on a background thread, what is the best way to handle this? Something like the following seems excessive but potentially necessary.
[[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修改。
You should send a message to the UI thread's dispatch queue and do your UI modifications from there.
喜欢这样:
dispatch_async(dispatch_get_main_queue(), ^{
// your code here
});
参见 Apple的Grand Central Dispatch文档
--- Dave
这篇关于由于NSUserDefaultsDidChangeNotification,后台线程的UI更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!