iOS - 关于 File's Owner 的一些事

用 nib 做过 UI 布局的朋友应该都会留意到,Interface Builder 里有个 File's Owner 的选项,但一般情况下我们不去管它也能在代码中相安无事地使用 nib。不过为了更清楚地了解程序的运行,下面用简单的例子说明,File's Owner 到底是怎么一回事。

先来上 Apple 的官方解释:

The File’s Owner object is a placeholder object that is not created when the nib file is loaded. Instead, you create this object in your code and pass it to the nib-loading code. The reason this object is so important is that it is the main link between your application code and the contents of the nib file. More specifically, it is the controller object that is responsible for the contents of the nib file.

In Xcode, you can create connections between the File’s Owner and the other interface objects in your nib file. When you load the nib file, the nib-loading code recreates these connections using the replacement object you specify. This allows your object to reference objects in the nib file and receive messages from the interface objects automatically.

主要意思是,File's Owner 只是 Interface Builder 里的一个占位符,用于方便你建立 view 与 controller(注意是 controller,因为除了 view controller 外你也可以使用任何父类是 NSObject 的类来作为 controller)之间的连接的。再直观点解释,就是让你可以用鼠标从 Interface Builder 拉 IBOutlet 到 controller 里。没有设置 File's Owner,你是不能引线的。

既然是占位符,在代码加载 nib 时,Interface Builder 的 File's Owner 设定是不会带到代码里的。意思就是,当你使用 loadNibNamed:owner:options: 加载 nib 时,owner 参数需要传入相同的 File's Owner,否则那些通过 Interface Builder 设定的 IBOutlet 就会失去连接,一旦当代码使用这些引用就会抛出异常,如下图:

没有设置 File's Owner 而引用 IBOutlet 的错误

举个例子,有一个 view,里面摆放了一个 label,同时设置好 File's Owner:


view

连接两个 IBOutlet 到对应的 view controller:


IBOutlet

留意最外层的 view 不是 weak 引用,是因为它是最顶层的父类,必须有一个强引用以保证其创建后不会被 ARC 回收。此时在 viewDidLoad 加载 nib:

加载 nib

这里不需要从 array 里取出对应的 view 并创建引用来指向它,因为参数 owner 中已经传入了 self(即当前 view controller),因此 nib 加载后会同时连上先前设置的 IBOutlet。(关于 IBOutlet 的更多解释,请点这里

不过本人不太喜欢这种隐性行为,不如把 owner 设置为 nil,然后通过代码来获取 view 的引用来得清晰明了。

总结

  • File's Owner 在 Interface Builder 里仅仅是一个占位符,用于建立与 controller 的 IBOutlet 连接,所以在 nib 加载时不会带到代码中。
  • 在 Interface Builder 建立里 IBOutlet 之后,通过 loadNibNamed:owner:options: 加载 nib 时,一定要传入对应的 owner,否则会抛出异常。

参考资料

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。