为什么我不应该在init / dealloc中使用Objective C 2.0访问器? [英] Why shouldn't I use Objective C 2.0 accessors in init/dealloc?

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

问题描述

@ mmalc的 response to 不使用访问器dealloc(或init)中的方法。为什么mmalc说这个?

In @mmalc's response to this question he states that "In general you should not use accessor methods in dealloc (or init)." Why does mmalc say this?

我可以想到的唯一真正的原因是性能和避免未知的@dynamic设置器的副作用。

The only really reasons I can think of are performance and avoiding unknown side-effects of @dynamic setters.

讨论?

推荐答案

这是关于使用一致的代码。如果你适当地模式所有的代码有一组规则,保证使用一个访问器在init / dealloc是安全的。

It is all about using idiomatically consistent code. If you pattern all of your code appropriately there are sets of rules that guarantee that using an accessor in init/dealloc is safe.

最大的问题是)代码设置属性默认状态不应该通过访问器,因为它导致各种各样的讨厌的问题。捕获是没有理由init必须设置属性的默认状态。由于很多原因,我一直在移动到自我初始化的访问器,如下面的简单例子:

The big issue is that (as mmalc said) the code the sets up the properties default state should not go through an accessor because it leads to all sorts of nasty issues. The catch is that there is no reason init has to setup the default state of a property. For a number of reasons I have been moving to accessors that self initialize, like the simple example below:

- (NSMutableDictionary *) myMutableDict {
    if (!myMutableDict) {
        myMutableDict = [[NSMutableDictionary alloc] init];
    }

    return myMutableDict;
}

这种风格的属性初始化允许延迟很多初始化代码,实际上没有必要。在上面的例子中,init不负责启动属性状态,并且对于在init方法中使用访问器是完全安全的(甚至是必要的)。

This style of property initialization allows one to defer a lot of init code that may not actually be necessary. In the above case init is not responsible for initing the properties state, and it is completely safe (even necessary) for one to use the accessors in the init method.

这会对您的代码施加额外的限制,例如,对超类中的属性的自定义访问器的子类必须调用超类访问器,但这些限制不符合Cocoa常见的其他限制。

Admittedly this does impose additional restrictions on your code, for instance, subclasses with custom accessors for a property in the superclass must call the superclasses accessor, but those restrictions are not out of line with various other restrictions common in Cocoa.

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

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