UI changes on background thread due to NSUserDefau

2019-02-11 06:00发布

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
}

1条回答
小情绪 Triste *
2楼-- · 2019-02-11 06:43

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

查看更多
登录 后发表回答