nib 加载过程分析以及对File’s Owner的理解

来源:互联网 发布:java教学视频高清 编辑:程序博客网 时间:2024/06/06 02:36
nib loading的过程,这个是app文档里面有说到资源编程指南

1. It loads the contents of the nib file and any referenced resource files into memory。将nib文件和其中引用到的资源文件加载到内存中。
2.It unarchives the nib object graph data and instantiates the objects。
解析nib对象,并对其进行实例化。对实例的对象初始化规则.
    a .By default, objects receive an initWithCoder: message.默认调用initWithCoder:.对于所有遵循NSCoding协议的对象,包括UIView和UIViewController的子类都会调用这个方法。
    b.Custom views in iOS do not use the initWithFrame: method for initialization.
   这针对于OS X。iOS的自定义view没有这个方法。所以这里忽略。
    c.Custom objects other than those described in the preceding steps receive an init message. 也就是其他对象将会调用init方法。

3. It reestablishes all connections (actions, outlets, and bindings) between objects in the nib file。重新为nib文件中的对象简历连接。包括placeholder对象的链接。
outlet的链接。In iOS, the nib-loading code uses the setValue:forKey: method to reconnect each outlet。iOS中使用的的mvc机制对其进行操作。
Action connections。in iOS, the nib-loading code uses the addTarget:action:forControlEvents: method of the UIControl object to configure the action. If the target is nil, the action is handled by the responder chain.使用的是addTarget:action:forControlEvents进行关联。如果目标是nil。那么这个action将会被相应链处理
Bindings。iOS不支持这个

4.It sends an awakeFromNib message to the appropriate objects in the nib file that define the matching selector:
     In iOS, this message is sent only to the interface objects that were instantiated by the nib-loading code. It is not sent to File’s Owner, First Responder, or any other placeholder objects.这个消息只会发送给再nib loading过程中实例化的对象,而不会给placeholder objects发送这个消息。


5. It displays any windows whose “Visible at launch time” attribute was enabled in the nib file. 


下面主要是分析connect的具体建立过程。

我们再xib中拖拽,不管是File's Owner还是再Object中进行的。都会再xib文件中保持这种链接关系。

这个是再object中建立的connect。其中包含有链接的源和目的目标,这个分别用ref做的标记。还有一个label,这就是我们的IBOutLet的名称了。



通过上面的xib的代码可以知道这个链接是和cell关联的,而不是和file‘s owner关联的。


下面再来看看和File’s owner关联的







看到了吧。其实你拖拽的链接关系都记录在了xib中了。再补充一个就是自定义类,很多时候我们都是要使用我们自定义的类。这个是再下面的图里面进行了描述。





到这里就差不多理解,nib再加载过程中是如何生成我们需要的对象,以及如果将IBOutLet和IBAction关联起来的了吧。细心的人可能注意到了File‘s Owner这个东西了,
那么这个对象又扮演着什么样的角色呢?

File's Owner是控制对象,可以说是nib文件的所有者,控制管理可视化对象。
这个和使用代码loadNibNamed中的owner是一样的意思。File's Owner作为占位符,是需要提前再使用nib加载之前存在的。我们一般将File‘s Owner设置为我们自己的Controller类,然后使用initWithNib来生成我们的Controller对象。其实 UIViewController是采用延迟加载的方式,只要需要使用view的时候才会真正的将nib加载起来,这个使用其实底下用的还是NSBundle的loadNibNamed这个方法,此时owner就是UIViewController了。这样我们在建立connect的时候就有了对象了。

除了File’s Owner作为那些使用File‘s Owner建立链接必须之外,File’s Owner还有负责内存管理的功能。这个可以参考IBOutlet内存管理,在apple给的文档中也有说明或者google/百度一下也可以。