创建 IBOutlet 是否太昂贵?

Is creating an IBOutlet too expensive?

不久前,我通过代码成为了 creating/manipulating 视图层次结构的粉丝。两者都是因为我认为更具表现力并迫使我更多地了解 Cocoa。

但我只写了 5 行代码,如果使用 IBOulet 看起来会更有表现力。它在具有特定标记的视图中查找子视图并向其发送消息。但是我可以很容易地创建一个 IBOutlet 并且只在一行中完成。

因此,我问:创建 IBOutlet 是不是太贵了?

P.S.: 让我们暂时切断 "readability over performance"。我真的很想知道这个的影响。

IBOutlet 是 Xcode 的标记,在预处理步骤结束时会被删除。在内部,设置它归结为将单个指针分配给 "backs" IBOutlet 属性 的实例变量。该指针在视图建立时分配,之后不会改变。很便宜。

另一方面,通过标签查找子视图是 运行 次操作,每次查找子视图时都需要 运行。通常它很便宜,但在具有大量子视图的视图中也可能变得相当昂贵。

因此,我肯定会选择 IBOutlet,因为它是一次性交易,而且因为它可以让您将代码从五行缩短为一行。

您必须能够找出当前方法的优缺点。事实上 Apple 的文档指出:

As with any item of object state, you should be able to justify its inclusion in a class; the more outlets an object has, the more memory it takes up. If there are other ways to obtain a reference to an object, such as finding it through its index position in a matrix, or through its inclusion as a function parameter, or through use of a tag (an assigned numeric identifier), you should do that instead.

在大多数情况下我更喜欢使用 IBOutlets,因为(我知道你不想听到这个)它们使代码更具可读性,当然正如@dasblinkenlight 指出的那样,你的遍历视图层次结构在运行时执行,因此随时(假设您在 viewDidLoad 中执行此操作)加载视图。

我的建议:坚持 IBOutlets,除非你有一个非常非常简单的视图层次结构并且使用标签来查找你的子视图是最好的解决方案。