Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can NSUserDefaults hold a NSArray with custom objects?

The title pretty much explains it. Do I need to serialize the objects first, or is it possible?

like image 472
Martol1ni Avatar asked Feb 11 '13 12:02

Martol1ni


2 Answers

You have to code/decode the objects in your object (which is in your array) with and archive the array to NSData.

Just add

<NSCoding>

to the Class of your Objects (in your array) and follow the warnings of your compiler :D

Then archive your array like this:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:yourArray];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:data forKey:@"yourKey"];


NSArray *array= [NSKeyedUnarchiver unarchiveObjectWithData:[defaults objectForKey:@"yourKey"];

Check this out http://soff.es/archiving-objective-c-objects-with-nscoding

like image 73
Wed Avatar answered Nov 03 '22 19:11

Wed


You need to serialize it.

From apple documentation for NSUSerDefaults:

The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object 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. If you want to store any other type of object, you should typically archive it to create an instance of NSData. For more details, see Preferences and Settings Programming Guide.

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html

like image 24
Khaled Barazi Avatar answered Nov 03 '22 20:11

Khaled Barazi