将包含另一个自定义对象的自定义对象保存到 NSUserDefaults 中 [英] saving custom object which contains another custom object into NSUserDefaults

查看:53
本文介绍了将包含另一个自定义对象的自定义对象保存到 NSUserDefaults 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解如何在 NSUser Defaults 中存储自定义对象,但是当我尝试使用内部对象的相同步骤来实现保存具有不同类型对象的对象时(如果我没记错的话,它被称为组合)正如我对第一个所做的那样,我遇到了运行时错误.您能否详细描述我必须采取的步骤才能正确保存和检索所有内容

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

推荐答案

你所有的对象都应该实现 NSCoding 协议.NSCoding 对将要保存的对象递归地工作.例如,您有 2 个自定义类

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;

要将 MyClass 对象保存到 NSUserDefaults,您需要为这两个类实现 NSCoding 协议:

For saving MyClass object to NSUserDefaults you need to implement NSCoding protocol to both these classes:

头等舱:

-(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;
}

二等舱:

-(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;
}

请注意,如果您的另一个类(上面的 MyAnotherClass)也有自定义对象,那么该自定义对象也应该实现 NSCoding.即使你有 NSArray 隐式包含自定义对象,你也应该为这些对象实现 NSCoding.

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.

这篇关于将包含另一个自定义对象的自定义对象保存到 NSUserDefaults 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆