写在前面

近几天花了一些时间了解了一下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. [delphi]修改indy源码后重新编译

    http://blog.csdn.net/nerdy/article/details/8702568 虽然indy有一身的毛病,但是一般情况下使用起来还是多方便的. 今天在做一个使用到indy的程序的 ...

  2. AC日记——A+B Problem(再升级) 洛谷 P1832

    题目背景 ·题目名称是吸引你点进来的 ·实际上该题还是很水的 题目描述 ·1+1=? 显然是2 ·a+b=? 1001回看不谢 ·哥德巴赫猜想 似乎已呈泛滥趋势 ·以上纯属个人吐槽 ·给定一个正整数n ...

  3. OSI模型详解

    OSI 七层模型通过七个层次化的结构模型使不同的系统不同的网络之间实现可靠的通讯,因此其最主要的功能就是帮助不同类型的主机实现数据传输 . 完成中继功能的节点通常称为中继系统.在OSI七层模型中,处于 ...

  4. VUE 自定义组件之间的相互通信

    一.自定义组件 1.全局自定义组件 我们在var vm = new Vue({});的上面并列写上Vue.component('自定义组件名',{组件对象});来完成全局自定义组件的声明.示例代码如下 ...

  5. CentOS6.5升级手动安装GCC4.8.2 与 CentOS 6.4 编译安装 gcc 4.8.1

    http://blog.163.com/zhu329599788@126/blog/static/6669335020161179259975 http://www.cnblogs.com/codem ...

  6. iOS--基于键值的观察者模式(KVO)

    VO简而言之就是:基于键值的观察者,实际上就是观察者模式. Cocoa Framework已经为我们提供了这一模式,不需要我们自己来实现了.我们只需要按照约定的方式去做就可以了.KVO主要用于用户界面 ...

  7. How to fill the background with image in landscape in IOS? 如何使image水平铺满屏幕

    UIImageView *backgroundImage = [[UIImageView alloc] initWithFrame:self.view.frame];    [backgroundIm ...

  8. windows redis 服务安装坑

    环境 winserver 2012 最新版的redis:3.0.503 redis-server.exe   --service-install   redis.windows.conf    --m ...

  9. 【转】LINUX 手动建立SWAP文件及删除

    如何在红帽 企业版Linux系统中添加swap文件? 解决方法: 1. 确定swap文件的大小,单位为M.将该值乘以1024得到块大小.例如,64MB的swap文件的块大小是65536. 2. 在ro ...

  10. react 中的无状态函数式组件

    无状态函数式组件,顾名思义,无状态,也就是你无法使用State,也无法使用组件的生命周期方法,这就决定了函数组件都是展示性组件,接收Props,渲染DOM,而不关注其他逻辑. 其实无状态函数式组件也是 ...