saving custom object which contains another custom

2019-06-09 07:42发布

问题:

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

回答1:

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.