8

I want to store an array with NSUserDefault, then, I put in applicationDidEnterBackground

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

and in application didFinishLaunchingWithOption

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

it's ok for multitasking device, but for not-multitasking device, how can I solve?

Alex Cio
  • 6,014
  • 5
  • 44
  • 74
cyclingIsBetter
  • 17,447
  • 50
  • 156
  • 241

6 Answers6

10

Store the object in NSUserDefaults in -applicationWillTerminate:, if it hasn't already been saved by the invocation of -applicationDidEnterBackground: (i.e. check if multitasking is supported, if it is, then don't save it because it's already been saved.)

- (void) applicationWillTerminate:(UIApplication *) app {
    if([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)] &&
       ![[UIDevice currentDevice] isMultitaskingSupported]) {
       [[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@"myArray"];
    }
}
Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • As pointed out in another answer, you need to synchronize the defaults after setting the object. [[NSUserDefaults standardUserDefaults] synchronize]; – user3246173 Sep 19 '15 at 18:28
7

Do not forget to sync the buffer before going into background:

[[NSUserDefaults standardUserDefaults] synchronize];
Vincent
  • 4,342
  • 1
  • 38
  • 37
3

The previous answers are all correct, but note that neither applicationDidEnterBackground nor applicationWillTerminate are guaranteed to be called in all situations. You are usually better off storing important data whenever it has changed.

fishinear
  • 6,101
  • 3
  • 36
  • 84
0

and don't forget to use the encodeWithCoder and initWithCoder inside the object that you are trying to save and that is contained in the array

Catalin
  • 1,821
  • 4
  • 26
  • 32
0

Save NSUserDefaults at

- (void)applicationWillTerminate:(UIApplication *)application 
kv0
  • 914
  • 10
  • 14
0

set

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

in

applicationWillTerminate
Saurabh Passolia
  • 8,099
  • 1
  • 26
  • 41