简体   繁体   中英

What is the correct way to unarchive data from NSuserDefaults?

I am storing some Objective C based objects in to NSuserdefaults.

To retrieve data from NSuserDefaults, I use initWithCoder method.

I have seen two different implementations of this:

Implementation 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

- (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). 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. 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).

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