Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS: store an array with NSUserDefault

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?

like image 928
cyclingIsBetter Avatar asked Sep 27 '11 14:09

cyclingIsBetter


People also ask

Can I store array in UserDefaults Swift?

You can only store arrays of strings, numbers, Date objects, and Data objects in the user's defaults database. Let's take a look at an example. We access the shared defaults object through the standard class property of the UserDefaults class.

How do I save an array of objects in Swift?

You'll need to convert the object to and from an NSData instance using NSKeyedArchiver and NSKeyedUnarchiver . For example: func savePlaces(){ let placesArray = [Place(lat: 123, lng: 123, name: "hi")] let placesData = NSKeyedArchiver. archivedDataWithRootObject(placesArray) NSUserDefaults.

How do you save a Userdefault string in Swift?

To store the string in the user's defaults database, which is nothing more than a property list or plist, we pass the string to the set(_:forKey:) method of the UserDefaults class. We also need to pass a key as the second argument to the set(_:forKey:) method because we are creating a key-value pair.


3 Answers

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"];
    }
}
like image 147
Jacob Relkin Avatar answered Sep 19 '22 16:09

Jacob Relkin


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

[[NSUserDefaults standardUserDefaults] synchronize];
like image 32
Vincent Avatar answered Sep 22 '22 16:09

Vincent


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.

like image 30
fishinear Avatar answered Sep 21 '22 16:09

fishinear