Objective-C中的+initialize和+load
写在前面
近几天花了一些时间了解了一下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:
- All initializers in any framework you link to.
- All +load methods in your image.
- All C++ static initializers and C/C++ attribute(constructor) functions in your image.
- 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中完成的,参考这里。
参考
- 《NSObject Class Reference》;
Objective-C中的+initialize和+load的更多相关文章
- iOS - + initialize 与 +load
一.+ initialize 方法和+load 调用时机 首先说一下 + initialize 方法:苹果官方对这个方法有这样的一段描述:这个方法会在 第一次初始化这个类之前 被调用,我们用它来初始化 ...
- iOS-方法之+ initialize 与 +load
Objective-C 有两个神奇的方法:+load 和 +initialize,这两个方法在类被使用时会自动调用.但是两个方法的不同点会导致应用层面上性能的显著差异. 一.+ initialize ...
- iOS之initialize与load
initialize和load 这两个方法都是是什么时候调用的呢?都有着什么样的作用,下面看看吧! initialize +(void)initialize{ } 什么时候调用:当第一次使用这个类的时 ...
- 理解Objective C 中id
什么是id,与void *的区别 id在Objective C中是一个类型,一个complier所认可的Objective C类型,跟void *是不一样的,比如一个 id userName, 和vo ...
- 浅谈Objective—C中的面向对象特性
Objective-C世界中的面向对象程序设计 面向对象称程序设计可能是现在最常用的程序设计模式.如何开发实际的程序是存在两个派系的-- 面向对象语言--在过去的几十年中,很多的面向对象语言被发明出来 ...
- objective C中的字符串NSStirng常用操作
objective C中的字符串操作 在OC中创建字符串时,一般不使用C的方法,因为C将字符串作为字符数组,所以在操作时会有很多不方便的地方,在Cocoa中NSString集成的一些方法,可以很方便的 ...
- Hibernate中的session和load延迟载入矛盾问题,怎样解决?
假设延迟载入出现session close的情况下 方法1.在web.xml中配置spring的openSessionInViewFilter <filter> <filter-n ...
- Flex中的initialize,creationComplete和applicationComp
转自:http://blog.csdn.net/sjz168/article/details/7244374 1.Application标签中有三个事件initialize,creationCompl ...
- Objective C中的ARC的修饰符的使用---- 学习笔记九
#import <Foundation/Foundation.h> @interface Test : NSObject /** * 默认的就是__strong,这里只是做示范,实际使用时 ...
随机推荐
- hdu1569 方格取数 求最大点权独立集
题意:一个方格n*m,取出一些点,要求两两不相邻,求最大和.思路:建图,相邻的点有一条边,则建立了一个二分图,求最大点权独立集(所取点两两无公共边,权值和最大),问题转化为求总权和-最小点权覆盖集(点 ...
- Lighttpd 服务器的安装
https://www.cnblogs.com/rongfengliang/articles/3503228.html
- mysql索引底层的数据结构和算法
1. 为什么要用索引 索引在MySQL中也叫做“键”,是存储引擎用于快速找到记录的一种数据结构.索引对于良好的性能非常关键,尤其是当表中的数据量越来越大时,索引对于性能的影响愈发重要. 索 ...
- seo优化入门教程:认识搜索引擎
对于从来没有学过seo或者零基础的人来说,搜索引擎可能都不太了解.所以我们先来认识搜索引擎有哪些,同时为什么我们要学习搜索引擎优化. 从目前全球的一个搜索引擎来说的话,他的分支是非常多的,甚至可以讲, ...
- 在springboot项目中获取pom.xml中的信息
最近做了一个新项目,用到了springboot.在搭建框架的过程中,需要读取pom.xml中version的值,本来想着是用自己用java解析xml来着.没想到maven提供了这么一个包,可以直接获取 ...
- 你还在为移动端选择器picker插件而捉急吗?
http://www.cnblogs.com/jingh/p/6381079.html 开题:得益于项目的上线,现在终于有时间来写一点点的东西,虽然很浅显,但是我感觉每经历一次项目,我就学到了很多的东 ...
- How to fill the background with image in landscape in IOS? 如何使image水平铺满屏幕
UIImageView *backgroundImage = [[UIImageView alloc] initWithFrame:self.view.frame]; [backgroundIm ...
- 【Spring boot】【gradle】idea新建spring boot+gradle项目
在此之前,安装了idea/jdk/gradle在本地 ===================================== gradle怎么安装:http://www.cnblogs.com/s ...
- springcloud 学习笔记
---恢复内容开始--- 1. pom配置 1.1 引入spring boot 依赖 <parent> <groupId>org.springframework.boot< ...
- C#3.0之神奇的Lambda表达式和Lambda语句
“Lambda 表达式”是一个匿名函数,它可以包含表达式和语句,并且可用于创建委托或表达式目录树类型.所有 Lambda 表达式都使用 Lambda 运算符 =>,该运算符读为“goes to” ...