开发者

Why does iOS NSDefaults require two launches to take effect?

开发者 https://www.devze.com 2023-02-07 23:23 出处:网络
I am working with NSUserDefaults in my iPhone app, and for some reason, the app needs to be launched/resumed twice for the changes in Settings to take effect.Relevant code:

I am working with NSUserDefaults in my iPhone app, and for some reason, the app needs to be launched/resumed twice for the changes in Settings to take effect. Relevant code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    ...

    DLog(@"Registered default user defaults values.");
    NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"DefaultUserDefaults" ofType:@"plist"]];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

    ...

}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    DLog(@"rescheduling notifications...");
    [self rescheduleAllNotifications];
}

- (void)rescheduleAllNotifications {
    //
    // Wipe the slate clean by cancelling all local notifications
    //
    [[UIApplication sharedApplication] cancelAllLocalNotifications];

    //
    // Only reschedule notifications if the user prefers to have them scheduled
    //
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults boolForKey:@"notifications_enabled_preference"]) {
        DLog(@"Notifications enabled. processing now...");

        ...

So here is my debugger output (starting with notifications_enabled_preference set to YES):

[Session started at 2011-01-31 14:25:58 -0600.]
AppDelegate application:didFinishLaunchingWithOptions:] Registered default user defaults values.
AppDelegate applicationDidBecomeActive:] reschedu开发者_JS百科ling notifications...
AppDelegate rescheduleAllNotifications] Notifications enabled. processing now...

-> Switch to Settings and turn notifications_enabled_preference to NO, then re-launch the app

AppDelegate applicationDidBecomeActive:] rescheduling notifications...
AppDelegate rescheduleAllNotifications] Notifications enabled. processing now...


-> Click home screen button, then re-launch the app **again**

AppDelegate applicationDidBecomeActive:] rescheduling notifications...
AppDelegate rescheduleAllNotifications] Notifications disabled. Skipping notification processing.

Why does it take launching the app twice for the changed settings to take effect?


NSUserDefaults synchronizes itself to the disk periodically (typically every 30 seconds or so). This synchronize process lets it write out changes to disk, but also pick up changes that were made on disk. Try sticking in a call to [[NSUserDefaults standardUserDefaults] synchronize] at the very top of your -applicationDidBecomeActive: method.

0

精彩评论

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