简体   繁体   English

从NSuserDefaults取消存档数据的正确方法是什么?

[英]What is the correct way to unarchive data from NSuserDefaults?

I am storing some Objective C based objects in to NSuserdefaults. 我将一些基于Objective C的对象存储到NSuserdefaults中。

To retrieve data from NSuserDefaults, I use initWithCoder method. 要从NSuserDefaults检索数据,我使用initWithCoder方法。

I have seen two different implementations of this: 我已经看到了两种不同的实现:

Implementation 1 实施1

- (id)initWithCoder:(NSCoder *)decoder {

     self = [super init];
    if (self != nil){

        //decode properties, other class vars
        self.variable = [decoder decodeObjectForKey:@"variable"];



    }
    return self;
}

Implementation 2 实施2

- (id)initWithCoder:(NSCoder *)decoder {

     self = [[CustomClass alloc] init];
    if (self != nil){

        //decode properties, other class vars
        self.variable = [decoder decodeObjectForKey:@"variable"];



    }
    return self;
}

Which is the correct way? 哪种方法正确?

What is the difference between these two? 两者有什么区别?

you shouldn't be alloc'ing your object in an method (the alloc takes place before init/initWithCoder is called). 您不应该在方法中分配对象(分配发生在调用init / initWithCoder之前)。 your code should look like: 您的代码应如下所示:

- (id)initWithCoder:(NSCoder *)decoder {
    self = [super initWithCoder:decoder];
    if (self != nil){
        //decode properties, other class vars
        self.variable = [decoder decodeObjectForKey:@"variable"];
    }
    return self;
}

This really isn't a difference in NSUserDefaults implementation, the difference whether or not your class is a subclass. 这确实不是NSUserDefaults实现的区别,无论您的类是否是子类,都没有区别。 Subclasses call [super init] to gain the properties of their superclasses (ex. 2), otherwise you can just alloc and init the custom class (ex. 1). 子类调用[super init]以获得其超类的属性(例如2),否则,您可以分配并初始化自定义类(例如1)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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