简体   繁体   中英

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.

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

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