What is the correct way to unarchive data from NSuserDefaults?

409 views Asked by At

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?

2

There are 2 answers

0
Nick On

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

1
Mike K On

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