Reputation: 17591
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?
Upvotes: 3
Views: 2767
Reputation: 3484
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.
Upvotes: 0
Reputation: 501
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.
Upvotes: 4