简体   繁体   中英

saving custom object which contains another custom object into NSUserDefaults

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM