fuzzygoat
fuzzygoat

Reputation: 26223

Using properties to access iVars in init?

This is an offshoot from a previous question, is this bad practice (using the property to set iVars)?

// Designated initializer 001
- (id)initWithName:(NSString *)newName andType:(NSString *)newType {
    self = [super init];
    if(self) {
        [self setName:newName];
        [self setType:newType];
    }
    return self;
}

or should I be using ...

// Designated initializer 002
- (id)initWithName:(NSString *)newName andType:(NSString *)newType {
    self = [super init];
    if(self) {
        name = [newName retain];
        type = [newType retain];
    }
    return self;
}

I have been using version 001, but have been led to believe that using properties to access iVars in either init or dealloc is bad practice.

EDIT: Added retain to version 002

Gary.

Upvotes: 3

Views: 962

Answers (1)

Chuck
Chuck

Reputation: 237010

Yes, Apple discourages using accessors in init or dealloc, because they can have side effects beyond merely setting an instance variable. These are obviously undesirable in an uninitialized or destroyed object.

Exact quote from the docs: "The only places you shouldn’t use accessor methods to set an instance variable are in init methods and dealloc."

Upvotes: 3

Related Questions