Is it possible to save an integer array using NSUserDefaults on the iPhone? I have an array declared in my .h file as: int playfield[9][11]
that gets filled with integers from a file and determines the layout of a game playfield. I want to be able to have several save slots where users can save their games. If I do:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject: playfield forKey: @"slot1Save"];
I get a pointer error. If it's possible to save an integer array, what's the best way to do so and then retrieve it later?
Thanks in advance!
You can save your mutable array like this: [[NSUserDefaults standardUserDefaults] setObject:yourArray forKey:@"YourKey"]; [[NSUserDefaults standardUserDefaults] synchronize]; Later you get the mutable array back from user defaults. It is important that you get the mutable copy if you want to edit the array later.
You can only store arrays of strings, numbers, Date objects, and Data objects in the user's defaults database.
NSUserDefaults caches the information to avoid having to open the user's defaults database each time you need a default value. When you set a default value, it's changed synchronously within your process, and asynchronously to persistent storage and other processes.
A property list, or NSUserDefaults can store any type of object that can be converted to an NSData object. It would require any custom class to implement that capability, but if it does, that can be stored as an NSData. These are the only types that can be stored directly.
You can save and retrieve the array with a NSData wrapper
ie (w/o error handling)
Save
NSData *data = [NSData dataWithBytes:&playfield length:sizeof(playfield)];
[prefs setObject:data forKey:@"slot1Save"];
Load
NSData *data = [prefs objectForKey:@"slot1Save"];
memcpy(&playfield, data.bytes, data.length);
From Apple's NSUserDefaults documentation:
A default’s value must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.
This is why you are getting the pointer error.
You have several options (in order of recommended usage):
NSArray
of NSArray
s to store playField
in your application
int
, but fill an NSArray with numbers before saving to NSUserDefaults
.
NSArchiver
to convert between an array of integers and NSData
.
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