为什么我不应该在init方法中使用访问器方法 [英] Why shoudn't I use accessor methods in init methods

查看:94
本文介绍了为什么我不应该在init方法中使用访问器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

摘自Apple文档中有关内存管理:

From Apple documentation about Memory Management :

您不应该使用访问器方法设置实例变量的唯一地方是init方法和dealloc.要使用一个数字对象代表零来初始化一个计数器对象,可以实现如下的init方法:

The only places you shouldn’t use accessor methods to set an instance variable are in init methods and dealloc. To initialize a counter object with a number object representing zero, you might implement an init method as follows:

要允许使用非零计数初始化计数器,您可以实现initWithCount:方法,如下所示:

To allow a counter to be initialized with a count other than zero, you might implement an initWithCount: method as follows:

- initWithCount:(NSNumber *)startingCount {
    self = [super init];
    if (self) {
        count = [startingCount copy];
    }
    return self;
}

为什么不呢?

推荐答案

请参阅我对

主要原因是因为子类可能会覆盖您的访问器并执行其他操作.子类的访问器可能假设一个完全初始化的对象,即子类的init方法中的所有代码都已运行.实际上,当您的init方法运行时,它们都没有.同样,子类的访问器可能取决于子类的dealloc方法未运行.当您的dealloc方法正在运行时,这显然是错误的.

The main reason why is because a subclass might override your accessors and do something different. The subclass's accessors might assume a fully initialised object i.e. that all the code in the subclass's init method has run. In fact, none of it has when your init method is running. Similarly, the subclass's accessors may depend on the subclass's dealloc method not having run. This is clearly false when your dealloc method is running.

要扩展您的示例(如果您已这样做的话)

To expand on your example, if you had instead done

- initWithCount:(NSNumber *)startingCount {
    self = [super init];
    if (self) {
        [self setCount: [startingCount copy]];
    }
    return self;
}

但是子类重写了setCount:除了设置count变量以外,还要执行其他操作,则可能会遇到麻烦.

but a subclass had overridden setCount: to do something other than set your count variable, you could be in trouble.

这篇关于为什么我不应该在init方法中使用访问器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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