在init中使用属性访问iVars? [英] Using properties to access iVars in init?

查看:70
本文介绍了在init中使用属性访问iVars?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个前一个问题的分支,这是不好的做法(使用属性设置iVars)?

  /指定的初始化器001 
- (id)initWithName:(NSString *)newName andType:(NSString *)newType {
self = [super init];
if(self){
[self setName:newName];
[self setType:newType];
}
return self;
}

或应该使用...



//指定的初始化器002
- (id)initWithName:(NSString *)newName andType:(NSString *)newType {
self = [super init];
if(self){
name = [newName retain];
type = [newType retain];
}
return self;
}

我一直在使用版本001,

EDIT:添加了 retain 到版本002



Gary。

解决方案

a href =http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html#//apple_ref/doc/uid/TP40004447-SW4 =nofollow >使用init或dealloc中的访问器阻止,因为它们可能具有超出仅设置实例变量的副作用。这些在未初始化或销毁的对象中显然是不受欢迎的。



从文档中精确引用:你不应该使用存取器方法来设置实例变量在init方法和dealloc中。


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

这篇关于在init中使用属性访问iVars?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆