Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 261
fuzzygoat Avatar asked Jan 30 '26 10:01

fuzzygoat


1 Answers

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

like image 139
Chuck Avatar answered Feb 01 '26 02:02

Chuck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!