8

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!

Chris Hanson
  • 54,380
  • 8
  • 73
  • 102
user21293
  • 6,439
  • 11
  • 44
  • 57

4 Answers4

13

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
  • 45,805
  • 17
  • 110
  • 144
  • It seems to work using memcpy(&playfield, data.bytes, data.length); instead of len.length. Thanks for the quick response! – user21293 Dec 08 '08 at 21:27
  • 1
    Consider using functions like OSSwapHostToLittleInt and OSSwapLittleToHostInt in case one day the iPhone OS changes to big-endian for some reason. – Chris Lundie Dec 08 '08 at 22:15
  • @epatel I used your code converting Array to Data & storing in NSUserDefaults but I am not able to get convert the data to Arrray.Is it possible to get the same data back in the Array using your code? – Ajay Sharma Feb 02 '12 at 13:05
8

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):

  1. Use an NSArray of NSArrays to store playField in your application
  2. Keep playField as an array of int, but fill an NSArray with numbers before saving to NSUserDefaults.
  3. Write your own subclass of NSArchiver to convert between an array of integers and NSData.
e.James
  • 116,942
  • 41
  • 177
  • 214
4

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

August
  • 12,139
  • 3
  • 29
  • 30
1

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

leonho
  • 3,563
  • 2
  • 21
  • 16