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?
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.
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.
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.
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"];
}
}
Do not forget to sync the buffer before going into background:
[[NSUserDefaults standardUserDefaults] synchronize];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With