Is NSUserDefaults being written to disk?

I write an index for the currently selected UITabBar in [NSUserDefaults standardUserDefaults], but I get a strange situation when the index is not written to disk. I use

// TO WRITE
NSNumber *selectedTab = [NSNumber numberWithInt:[tabBarController selectedIndex]];
[[NSUserDefaults standardUserDefaults] setObject:selectedTab forKey:@"selectedTab"];

and...

// TO READ
NSNumber *selectTab = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectedTab"];
NSLog(@"SelectTab: %@", selectTab);
[tabController setSelectedIndex:[selectTab intValue]];

Can someone tell me if it setObject:forKey:is actually writing to disk, or do I need to force the recording to use something like synchronize?

+3
source share
3 answers

You need to call synchronize, although it is automatically called automatically (at least according to the documentation). A good time to call it is in the application delegate applicationWillEnterBackground:and applicationWillTerminate:.

+6
source

. , , .

[[NSUserDefaults standardUserDefaults] synchronize];

applicationWillResignActive.

+3

The synchronization method is called automatically at periodic intervals. You can also call it directly if you cannot wait for periodic intervals. The Apple documentation gives an example of a synchronization call if your application is about to exit.

See: NSUserDefaults class reference

+2
source

Source: https://habr.com/ru/post/1777703/


All Articles