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

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

问题描述

@mmalc 的 回应 这个问题 他指出一般来说,你应该使用访问器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 setter 的未知副作用.

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.

最大的问题是(正如 mmalc 所说)设置属性默认状态的代码不应该通过访问器,因为它会导致各种令人讨厌的问题.问题是没有理由 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天全站免登陆