I understand how to store a custom object in NSUser Defaults but when i tried to implement saving an object with an object of different type inside it (it is called composition if i'm not mistaken) following the same steps for inner object as i did for the first one i got runtime error. Could you please minutely describe steps that i have to undertake in order to save and retrieve everything correctly
Asked
Active
Viewed 918 times
0
-
1Show us what you did (your code) and we'll tell you what's wrong with it. – rob mayoff Oct 27 '11 at 18:42
1 Answers
4
All your objects should implement NSCoding protocol. NSCoding works recursively for objects that would be saved. For example, you have 2 custom classes
@interface MyClass : NSObject {
}
@property(nonatomic, retain) NSString *myString;
@property(nonatomic, retain) MyAnotherClass *myAnotherClass;
@interface MyAnotherClass : NSObject {
}
@property(nonatomic, retain) NSNumber *myNumber;
For saving MyClass object to NSUserDefaults you need to implement NSCoding protocol to both these classes:
For first class:
-(void)encodeWithCoder:(NSCoder *)encoder{
[encoder encodeObject:self.myString forKey:@"myString"];
[encoder encodeObject:self.myAnotherClass forKey:@"myAnotherClass"];
}
-(id)initWithCoder:(NSCoder *)decoder{
self = [super init];
if ( self != nil ) {
self.myString = [decoder decodeObjectForKey:@"myString"];
self.myAnotherClass = [decoder decodeObjectForKey:@"myAnotherClass"];
}
return self;
}
For second class:
-(void)encodeWithCoder:(NSCoder *)encoder{
[encoder encodeObject:self.myNumber forKey:@"myNumber"];
}
-(id)initWithCoder:(NSCoder *)decoder{
self = [super init];
if ( self != nil ) {
self.myNumber = [decoder decodeObjectForKey:@"myNumber"];
}
return self;
}
Note, if your another class (MyAnotherClass above) has also custom object then that custom object should implement NSCoding as well. Even you have NSArray which implicity contains custom objects you should implement NSCoding for these objects.

beryllium
- 29,669
- 15
- 106
- 125
-
can you please tell me in your First class i have a array with MyAnotherClass. How can i use NSCoding. – Kittu Jun 16 '15 at 14:27
-
I'm pretty sure that you cannot do this. http://stackoverflow.com/a/19720674/8047 You need to convert to `NSData` first. – Dan Rosenstark Aug 20 '15 at 19:01