IOS杂笔- 7(类方法load与initialize的区别 浅析)

本文详细解析了Objective-C中初始化(initialize)与加载(load)两个类方法的区别与联系,包括它们的调用时机、调用顺序及应用场景。初始化方法在类或其子类首次被调用前执行一次,而加载方法则在类被动态加载或静态链接时调用。

在介绍两种类方法之前,NSObject Class Reference里对这两个方法说明:

+(void)initialize

The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.) The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.

翻译:运行库在一个程序中每一个类的一个程序中发送一个初始化一次,或是从它继承的任何类中,都是在程序中发送第一条消息。(因此,当该类不使用时,该方法可能永远不会被调用。)运行时发送一个线程安全的方式初始化消息。收到这个消息之前,他们的子类父类。

+(void)load

The load message is sent to classes and categories that are both dynamically loaded and statically linked, but only if the newly loaded class or category implements a method that can respond.
The order of initialization is as follows:

  1. All initializers in any framework you link to.
  2. All +load methods in your image.
  3. All C++ static initializers and C/C++ __attribute__(constructor) functions in your image.
  4. All initializers in frameworks that link to you.

In a custom implementation of load you can therefore safely message other unrelated classes from the same image, but any loadmethods implemented by those classes may not have run yet.

翻译:加载消息被发送到动态加载和静态链接的类和类别,但只有当新加载的类或类实现了可以响应的方法。初始化的顺序如下:

在任何框架链接到你所有的初始化。

所有的负载方法在您的图像。

所有c++静态初始化器和C / c++使用__attribute__(构造函数)函数在你的形象

所有初始化框架链接到你。

在一个自定义实现负载可以因此安全消息其他不相关的类相同的图像,但任何负载方法的实现类可能尚未运行。

------------------------------------------------

Apple的文档很清楚地说明了initialize和load的区别在于:load是只要类所在文件被引用就会被调用,而initialize是在类或者其子类的第一个方法被调用前调用。所以如果类没有被引用进项目,就不会有load调用;但即使类文件被引用进来,但是没有使用,那么initialize也不会被调用。

它们的相同点在于:方法只会被调用一次。(其实这是相对runtime来说的,后边会做进一步解释)。

文档也明确阐述了方法调用的顺序:父类(Superclass)的方法优先于子类(Subclass)的方法,类中的方法优先于类别(Category)中的方法。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值