写在前面

近几天花了一些时间了解了一下Objective-C runtime相关的东西,其中涉及到了+load方法,譬如method swizzling通常在category的+load方法中完成。之前对initializer和load的使用就比较疑惑,但一直没有详细去对比了解,以此为契机,集各方资源,分析一下吧!

关于了解+initialize+load,个人感觉参考官方文档《NSObject Class Reference》就够了。

+initialize

关于+initialize方法,《NSObject Class Reference》的介绍如下:

Initializes the class before it receives its first message.

可以理解+initialize的作用是为了该Class在使用前创建合适的环境;

关于其使用,《NSObject Class Reference》的说明如下:

The runtime sends initialize to each class in a program just before the class, or any class that inherits from it, is sent its first message from within the program. The runtime sends the initialize message to classes in a thread-safe manner. Superclasses receive this message before their subclasses. The superclass implementation may be called multiple times if subclasses do not implement initialize—the runtime will call the inherited implementation—or if subclasses explicitly call [super initialize].

这上面这段话,可以得出如下这么一些意思:

  • +initialize方法是在runtime被调用的;
  • 对于某个类,其类+initialize方法都会在该对象接受任何消息之前被调用;
  • 如果父类和子类的+initialize方法都被调用,父类的调用一定在子类之前,这是系统自动完成的,子类+initialize中没必要显式调用[super initialize];
  • runtime系统处理+initialize消息的方式是线程安全的,所以没必要在+initialize中为了保证线程安全而使用lock、mutex之类的线程安全工具;
  • 某个类的+initialize的方法不一定只被调用一次,至少有两种情况会被调用多次:
    • 子类显式调用[super initialize];
    • 子类没有实现+initialize方法;

下面以示例演示某个类的+initialize被多次执行的现象。

定义三个类:Person、Student、Teacher,Student和Teacher继承自Person,Person继承自NSObject。Person和Student都实现了+initialize方法,Teacher没有实现该方法,如下:

// Person的+initialize方法的实现
+ (void)initialize {
NSLog(@"Person initialize");
} // Student的+initialize方法的实现
+ (void)initialize {
NSLog(@"Student initialize");
}

执行效果如下:

- (void)viewDidLoad {
Student *aStudent = [[Student alloc] init];
Teacher *aTeacher = [[Teacher alloc] init]; [super viewDidLoad];
} /* 输出:
Person initialize
Student initialize
Person initialize
*/

可以看到,对于Student,在其+initialize方法被调用之前,其super class(Person)的+initialize方法被率先调用;对于Teacher,没有定义+initialize方法,所以它会直接调用super class(Person)的+initialize方法,这就导致了Person的+initialize方法被执行两次。

有没有办法避免Person的+initialize方法被多次调用?当然可以:

// Person的+initialize方法的实现
+ (void)initialize {
static BOOL b = false;
if (!b) {
NSLog(@"Person initialize");
b = true;
}
}

也可以这样:

// Person的+initialize方法的实现
+ (void)initialize {
if (self == [Person class]) {
NSLog(@"Person initialize");
}
}

《NSObject Class Reference》中还对+initialize方法的使用做了一些警告:

Because initialize is called in a thread-safe manner and the order of initialize being called on different classes is not guaranteed, it’s important to do the minimum amount of work necessary in initialize methods. Specifically, any code that takes locks that might be required by other classes in their initialize methods is liable to lead to deadlocks. Therefore you should not rely on initialize for complex initialization, and should instead limit it to straightforward, class local initialization.

总结一下,就是这样:

  • 不要在+initialize中处理复杂的逻辑;

那么+initialize可以做些什么事情呢?可以做一些简单的初始化工作,譬如对于某个继承自UICollectionViewCell的自定义类PhotoViewCell,PhotoViewCell的对象可能会有一些公用资源,譬如label color,label font等等,没必要在-initXXOO方法中创建这些完全一样的资源,此时就可以放在PhotoViewCell中的+initialize中完成,如下:

+ (void)initialize {
titleFont = [UIFont systemFontOfSize:12];
titleHeight = 20.0f;
videoIcon = [UIImage imageNamed:@"CTAssetsPickerVideo"];
titleColor = [UIColor whiteColor];
checkedIcon = [UIImage imageNamed:@"CTAssetsPickerChecked"];
selectedColor = [UIColor colorWithWhite:1 alpha:0.3];
}

+initialize终究还是带来惊人的信息量,颇为失望。

+load

二者都户只执行一次(在不考虑开发者主动使用的情况下,系统最多会调用一次);
load在类被加载到系统时执行;
如果父类和子类都被调用,父类的调用一定在子类之前
都是为了应用运行提前创建合适的运行环境
在使用时都不要过重地依赖于这两个方法,除非真正必要

关于+load方法,《NSObject Class Reference》的介绍如下:

Invoked whenever a class or category is added to the Objective-C runtime; implement this method to perform class-specific behavior upon loading.

关于其使用,《NSObject Class Reference》的说明如下:

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 addition:

  • A class’s +load method is called after all of its superclasses’ +load methods.
  • A category +load method is called after the class’s own +load method.
    In a custom implementation of load you can therefore safely message other unrelated classes from the same image, but any load methods implemented by those classes may not have run yet.

从这段文字可以读出如下信息:

  • 在一个程序(main函数)运行之前,所用到的库被加载到runtime之后,被添加到的runtime系统的各种类和category的+load方法就被调用;(关于这点很容易通过打印语句来验证);
  • 如果父类和子类的+load方法都被调用,父类的调用一定在子类之前,这是系统自动完成的,子类+load中没必要显式调用[super load];
  • 文档没有讲明+load的执行是否是线程安全的,但考虑到它是在runtime之前就调用,所以谈论它是否是线程安全没啥必要,根据我的理解,多线程在runtime才有谈论意义;
  • 若某个类由一个主类和多个category组成,则允许主类和category中各自有自己的+load方法,只是category中的+load的执行在主类的+load之后;

关于+load的使用场景,笔者知道的至少有一个,method swizzling的处理一般都在category的+load中完成的,参考这里

参考

    1. 《NSObject Class Reference》;

Objective-C中的+initialize和+load的更多相关文章

  1. iOS - + initialize 与 +load

    一.+ initialize 方法和+load 调用时机 首先说一下 + initialize 方法:苹果官方对这个方法有这样的一段描述:这个方法会在 第一次初始化这个类之前 被调用,我们用它来初始化 ...

  2. iOS-方法之+ initialize 与 +load

    Objective-C 有两个神奇的方法:+load 和 +initialize,这两个方法在类被使用时会自动调用.但是两个方法的不同点会导致应用层面上性能的显著差异. 一.+ initialize ...

  3. iOS之initialize与load

    initialize和load 这两个方法都是是什么时候调用的呢?都有着什么样的作用,下面看看吧! initialize +(void)initialize{ } 什么时候调用:当第一次使用这个类的时 ...

  4. 理解Objective C 中id

    什么是id,与void *的区别 id在Objective C中是一个类型,一个complier所认可的Objective C类型,跟void *是不一样的,比如一个 id userName, 和vo ...

  5. 浅谈Objective—C中的面向对象特性

    Objective-C世界中的面向对象程序设计 面向对象称程序设计可能是现在最常用的程序设计模式.如何开发实际的程序是存在两个派系的-- 面向对象语言--在过去的几十年中,很多的面向对象语言被发明出来 ...

  6. objective C中的字符串NSStirng常用操作

    objective C中的字符串操作 在OC中创建字符串时,一般不使用C的方法,因为C将字符串作为字符数组,所以在操作时会有很多不方便的地方,在Cocoa中NSString集成的一些方法,可以很方便的 ...

  7. Hibernate中的session和load延迟载入矛盾问题,怎样解决?

    假设延迟载入出现session close的情况下 方法1.在web.xml中配置spring的openSessionInViewFilter <filter>  <filter-n ...

  8. Flex中的initialize,creationComplete和applicationComp

    转自:http://blog.csdn.net/sjz168/article/details/7244374 1.Application标签中有三个事件initialize,creationCompl ...

  9. Objective C中的ARC的修饰符的使用---- 学习笔记九

    #import <Foundation/Foundation.h> @interface Test : NSObject /** * 默认的就是__strong,这里只是做示范,实际使用时 ...

随机推荐

  1. Controller配置汇总

    1.通过Url对应Bean <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping ...

  2. Chrome查看DNS状态提示:DNS pre-resolution and TCP pre-connection is disabled.

    chrome://dns 别试了,在这个功能在旧版可以通过关闭预读可以实现,但是新版的不行. 但是可以通过这种方式替代: chrome://net-internals/#dns 这个方式更直观,可以看 ...

  3. Ubuntu下Deb软件包相关安装与卸载

    安装deb软件包 sudo dpkg -i xxx.deb 删除软件包 sudo dpkg -r xxx.deb 连同配置文件一起删除 sudo dpkg -r --purge xxx.deb 查看软 ...

  4. 如何使用NSOperations和NSOperationQueues 第一部分

    这篇文章还可以在这里找到 英语 学习如何在你的app中使用NSOperations! 这篇博客是由iOS个人开发者Soheil Moayedi Azarpour发布的. 每个人都会在使用iOS或者Ma ...

  5. 第24章、OnLongClickListener长按事件(从零开始学Android)

    在Android App应用中,OnLongClick事件表示长按2秒以上触发的事件,本章我们通过长按图像设置为墙纸来理解其具体用法. 知识点:OnLongClickListener OnLongCl ...

  6. Codeforces Round #258 (Div. 2/A)/Codeforces451A_Game With Sticks

    解题报告 http://blog.csdn.net/juncoder/article/details/38102263 n和m跟木棍相交,问一人取一交点(必须是交点.且取完后去掉交点的两根木棍),最后 ...

  7. Servlet的部署开发细节以及注意事项

    学习servlet最困难的我感觉还是配置,一開始是非常麻烦的.为了较好的学习,一開始还是以手动开发我认为比較好,可是真的有点把握给搞晕了,尤其是部署servlet方面非常麻烦,这里做一下简单的总结,前 ...

  8. hunnu--11545--小明的烦恼——找路径

    小明的烦恼--找路径  Time Limit: 2000ms, Special Time Limit:5000ms, Memory Limit:32768KB Total submit users:  ...

  9. SIFT算法中DoG特征点的修正

    SIFT算法中,在DoG空间找到极值点后,需要对极值点进行修正,本文主要详细的讲解一下为什么需要修正,以及如何对极值点进行修正. 下图演示了二维函数离散空间得到的极值点与连续空间的极值点之间的差别 利 ...

  10. jquery事件手冊

    方法 描写叙述 bind() 向匹配元素附加一个或很多其它事件处理器 blur() 触发.或将函数绑定到指定元素的 blur 事件 change() 触发.或将函数绑定到指定元素的 change 事件 ...