NSUserDefaultsDidChangeNotification not sent when app resumes from the background

依然范特西╮ 提交于 2019-12-02 18:41:10

问题


Apple's documentation says that "the system queues many relevant notifications and delivers them to the app as soon as it starts executing code again (either in the foreground or background)", including NSUserDefaultsDidChangeNotification, but my app is not receiving it. Here's a log trace of relevant events:

2013-06-25 16:23:36.857 -[DPLAppDelegate applicationWillResignActive:] [debug]: end willResignActive
2013-06-25 16:23:36.859 -[DayViewController handlePreferenceChange:] [debug]: day controller received user defaults did change notification
2013-06-25 16:23:36.970 -[AppDelegate applicationDidEnterBackground:] [debug]: end didEnterBackground

// Here I go into Settings app and change something that should trigger userdefaultsdidchange

2013-06-25 16:23:52.043 -[AppDelegate applicationWillEnterForeground:] [debug]: end willEnterForeground
2013-06-25 16:23:52.045 -[AppDelegate applicationDidBecomeActive:] [debug]: end didBecomeActive

Here's the relevant code, I think:

AppDelegate.m

- (void)applicationDidEnterBackground:(UIApplication *)application 
{
// save our last active day
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:kLastActiveTimeDefault];
[[NSUserDefaults standardUserDefaults] synchronize];

DLog(@"end didEnterBackground");
}

DayViewController.m

- (void)viewDidLoad
{
    [[NSNotificationCenter defaultCenter]
        addObserver:self selector:@selector(handlePreferenceChange:) name:NSUserDefaultsDidChangeNotification object:nil];
}

- (void)handlePreferenceChange:(NSNotification *)note
{
    DLog(@"received user defaults did change notification");
    // do stuff
    [self updateDisplay];
}

What's supposed to happen is that the user makes a change in Settings, which posts NSUserDefaultsDidChangeNotification, which gets sent to -handlePreferenceChange, which updates some data and refreshes the display.

But the NSUserDefaultsDidChangeNotification is not happening on resume. I can see that I'm subscribed to the notification, because it gets triggered by my bookkeeping update to kLastActiveTimeDefault -willResignActive:

I've tried commenting out the bookkeeping for lastActiveTime, in case somehow the notification coalescing function was getting messed up, but it doesn't seem to change anything. So what's up? Apple's pretty clear that iOS is supposed to save notifications for me from Settings changes that happen while my app is asleep, but it's not happening.

来源:https://stackoverflow.com/questions/17307456/nsuserdefaultsdidchangenotification-not-sent-when-app-resumes-from-the-backgroun

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!