开发者

UI changes on background thread due to NSUserDefaultsDidChangeNotification

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 back开发者_如何学JAVAground 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
}


You should send a message to the UI thread's dispatch queue and do your UI modifications from there.

Like this:

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

See Apple's Grand Central Dispatch documentation

--- Dave

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜