开发者

Storing NSMutableArray with NSUserDefaults

开发者 https://www.devze.com 2023-03-05 08:34 出处:网络
In my project I use an NSMutableArray in my app delegate with NSUserDefaults: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

In my project I use an NSMutableArray in my app delegate with NSUserDefaults:

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

array = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"array"]]; 

and

- (void)applicationWillTerminate:(UIApplication *)application {

    [[NSUserDefaults standardUserDefaults] setObject:array forKey:@"array"]; 

the problem is that whe开发者_运维知识库n I write in a class, for example, firstViewController.m, in viewdidload:

NSLog(@"number of element:%d", appDelegate.array.count);

the result is always "2" but if I write

[appDelegate.array removeAllObjects];

then the result of count is "0". When I restart the app the count is again "2". What can I do to have zero objects inside the array when I restart the application?


You need to add a call to -[NSUserDefaults synchronize] after updating the "array" value in applicationWillTerminate. Normally, this is called periodically for you, but in your case you are updating the value at termination, so you need to explicitly cause it to be saved before exiting.


Under multitasking, applicationWillTerminate: usually isn't called before the app is killed. You could update user defaults with the new array value right after you change it (and, yes, call synchronize afterwards) or if for some reason you really want to delay saving to user defaults, you could use the UIApplication applicationWillResignActive: delegate method instead.

0

精彩评论

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