Codesen
Codesen

Reputation: 7822

How to store custom object in User Defaults - IOS

I created one custom class & created object for that class. I want to store that object into NSUserDefault. I am getting error while set the object into userfaults. How can I set?

Upvotes: 1

Views: 1828

Answers (3)

Codesen
Codesen

Reputation: 7822

You have to implement the NSCoding protocol in your class & implement the protocols methods. This is simply serialization. While storing the object you should serialize(NSKeyedArchiver) the class & same as retrieval you should unserialize(NSKeyedUnArchiver) that object.

the methods are

  • (void)encodeWithCoder:(NSCoder *)aCoder;
  • (id)initWithCoder:(NSCoder *)aDecoder;

Upvotes: 3

Gordon Dove
Gordon Dove

Reputation: 2577

The most probably reason is that you have something hard to archive in your structure.

Here is a quote from the NSUserDefaults Class Reference that you might find useful:

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.

Edit. Beaten to the punch by Stephen, give the man a prize :)

Upvotes: 0

Stephen Darlington
Stephen Darlington

Reputation: 52565

As the documentation states:

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.

The simplest way of creating an instance of NSData is by using an NSKeyedArchiver.

Upvotes: 0

Related Questions