saving custom object which contains another custom object into NSUserDefaults

有些话、适合烂在心里 提交于 2019-12-08 12:46:27

问题


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.



来源:https://stackoverflow.com/questions/7920682/saving-custom-object-which-contains-another-custom-object-into-nsuserdefaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!