0

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?

RK-
  • 12,099
  • 23
  • 89
  • 155

2 Answers2

1

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;
}
Mike K
  • 2,227
  • 1
  • 12
  • 6
  • initWithCoder is a member of NSCoding protocol. NSObject does not implement NSCoding (you have to declare it explicitly for your own class), so you cannot call [super initWithCoder:decorder] from a class that directly derived from NSObject. – interrupt Sep 30 '13 at 03:16
0

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

Nick
  • 9,792
  • 7
  • 50
  • 60