开发者

NSUserDefaults write to disk?

I am writing an index for the currently selected UITabBar to [NSUserDefaults standardUserDefaults] but I am getting the odd situation where the index is not writen to disk. I am using

// 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 anyone tell me if setObj开发者_C百科ect:forKey: does the actual write to disk, or do I need to force the write using something like synchronize ?


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


Yes. You need to call synchronize to make sure your changes are actually written.

[[NSUserDefaults standardUserDefaults] synchronize];

Usually it's done in applicationWillResignActive handler.


The synchronize method is called automatically at periodic intervals. You can also call it directly if you can't wait for the periodic intervals. Apple's documentation gives the example of calling synchronize if your application is about to exit.

See: NSUserDefaults Class Reference

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜