views:

4779

answers:

4

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!

+3  A: 

You'll have to convert this to an object. You can use NSArray or NSDictionary.

August
+6  A: 

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);
epatel
It seems to work using memcpy( instead of len.length. Thanks for the quick response!
Consider using functions like OSSwapHostToLittleInt and OSSwapLittleToHostInt in case one day the iPhone OS changes to big-endian for some reason.
Chris Lundie
+4  A: 
e.James
A: 

Just use NSArray instead of normal C array then it will solve your problem easily.

leonho