Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to save an integer array using NSUserDefaults on iPhone?

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!

like image 571
user21293 Avatar asked Dec 08 '08 20:12

user21293


People also ask

How do I save an array in NSUserDefaults in Objective C?

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.

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.

How does NSUserDefaults work?

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.

What is NSUserDefaults in swift?

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.


2 Answers

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);
like image 177
epatel Avatar answered Nov 15 '22 19:11

epatel


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.
like image 29
e.James Avatar answered Nov 15 '22 20:11

e.James