Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing NSMutableArray with NSUserDefaults

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 when 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?

like image 214
cyclingIsBetter Avatar asked Nov 22 '25 07:11

cyclingIsBetter


1 Answers

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.

like image 129
ondmike Avatar answered Nov 23 '25 22:11

ondmike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!