由于 NSUserDefaultsDidChangeNotification,后台线程上的 UI 发生变化
我正在调试一个问题,该问题偶尔会导致我的应用程序崩溃,并在崩溃报告中显示 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
}
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.
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该向 UI 线程的调度队列发送一条消息,并从那里进行 UI 修改。
像这样:
请参阅 Apple 的 Grand Central Dispatch 文档< /a>
--- 戴夫
You should send a message to the UI thread's dispatch queue and do your UI modifications from there.
Like this:
See Apple's Grand Central Dispatch documentation
--- Dave