开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜