一、基本使用
- 1卡骂、RevanPerson類
#import <Foundation/Foundation.h>
@interface RevanPerson : NSObject
- (void)test;
@end
#import "RevanPerson.h"
@implementation RevanPerson
- (void)test {
NSLog(@"RevanPerson -test");
}
@end
- 2、RevanPerson+RevanRun
#import "RevanPerson.h"
@interface RevanPerson (RevanRun)
- (void)run;
@end
#import "RevanPerson+RevanRun.h"
@implementation RevanPerson (RevanRun)
- (void)run {
NSLog(@"RevanPerson (RevanRun) -run");
}
@end
- 3、RevanPerson+RevanSleep
#import "RevanPerson.h"
@interface RevanPerson (RevanSleep)
- (void)sleep;
@end
#import "RevanPerson+RevanSleep.h"
@implementation RevanPerson (RevanSleep)
- (void)sleep {
NSLog(@"RevanPerson (RevanSleep) -sleep");
}
@end
- 測試代碼
#import "ViewController.h"
#import "RevanPerson.h"
#import "RevanPerson+RevanRun.h"
#import "RevanPerson+RevanSleep.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
RevanPerson *person = [[RevanPerson alloc] init];
[person test];
[person run];
[person sleep];
}
@end
打印輸出:
2018-07-01 22:55:34.571809+0800 01-Category[7688:454393] RevanPerson -test
2018-07-01 22:55:34.572009+0800 01-Category[7688:454393] RevanPerson (RevanRun) -run
2018-07-01 22:55:34.572131+0800 01-Category[7688:454393] RevanPerson (RevanSleep) -sleep
- 常用Category給類添加方法
二宰翅、Category的底層結(jié)構(gòu)類型
xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc
RevanPerson+RevanRun.m -o RevanPerson+RevanRun.cpp
- Category結(jié)構(gòu)類型,是struct _category_t 結(jié)構(gòu)體類型
struct _category_t {
const char *name;//類名
struct _class_t *cls;//類
const struct _method_list_t *instance_methods;//實例對象方法列表
const struct _method_list_t *class_methods;//實例對象方法列表
const struct _protocol_list_t *protocols;//協(xié)議列表
const struct _prop_list_t *properties;//屬性列表
};
- 為了看到更加詳細(xì)的各個參數(shù)的情況爽室,給分類再添加一些屬性汁讼、代理、協(xié)議
#import "RevanPerson.h"
#import <UIKit/UIKit.h>
@protocol RevanPerson_RevanRunDelegate
- (void)RevanPerson_RevanRunDelegate_tableData;
- (void)RevanPerson_RevanRunDelegate_tableDelegate;
@end
@interface RevanPerson (RevanRun)<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, weak) id<RevanPerson_RevanRunDelegate> delegate;
@property (nonatomic, assign) CGFloat speed;
- (void)run;
@end
#import "RevanPerson+RevanRun.h"
@implementation RevanPerson (RevanRun)
- (void)run {
NSLog(@"RevanPerson (RevanRun) -run");
}
@end
- 1阔墩、查看RevanPerson+RevanRun源碼
_OBJC_$_CATEGORY_RevanPerson_$_RevanRun的賦值情況
static struct _category_t _OBJC_$_CATEGORY_RevanPerson_$_RevanRun __attribute__ ((used, section ("__DATA,__objc_const"))) =
{
"RevanPerson",
0, // &OBJC_CLASS_$_RevanPerson,
(const struct _method_list_t *)&_OBJC_$_CATEGORY_INSTANCE_METHODS_RevanPerson_$_RevanRun,
0,
(const struct _protocol_list_t *)&_OBJC_CATEGORY_PROTOCOLS_$_RevanPerson_$_RevanRun,
(const struct _prop_list_t *)&_OBJC_$_PROP_LIST_RevanPerson_$_RevanRun,
};
- 2嘿架、對象方法列表
_OBJC_$_CATEGORY_INSTANCE_METHODS_RevanPerson_$_RevanRun是一個結(jié)構(gòu)體:類型如下
static struct /*_method_list_t*/ {
unsigned int entsize; // sizeof(struct _objc_method)
unsigned int method_count;
struct _objc_method method_list[1];
}
在對象方法列表(一個數(shù)組):發(fā)現(xiàn)有run方法
static struct /*_method_list_t*/ {
unsigned int entsize; // sizeof(struct _objc_method)
unsigned int method_count;
struct _objc_method method_list[1];
} _OBJC_$_CATEGORY_INSTANCE_METHODS_RevanPerson_$_RevanRun __attribute__ ((used, section ("__DATA,__objc_const"))) = {
sizeof(_objc_method),
1,
{{(struct objc_selector *)"run", "v16@0:8", (void *)_I_RevanPerson_RevanRun_run}}
};
- 3、協(xié)議列表
_OBJC_CATEGORY_PROTOCOLS_$_RevanPerson_$_RevanRun是一個結(jié)構(gòu)體類型啸箫,結(jié)構(gòu)如下:
static struct /*_protocol_list_t*/ {
long protocol_count; // Note, this is 32/64 bit
struct _protocol_t *super_protocols[2];
}
在給協(xié)議列表_OBJC_CATEGORY_PROTOCOLS_$_RevanPerson_$_RevanRun賦值中可以看到遵守的2個協(xié)議
static struct /*_protocol_list_t*/ {
long protocol_count; // Note, this is 32/64 bit
struct _protocol_t *super_protocols[2];
} _OBJC_CATEGORY_PROTOCOLS_$_RevanPerson_$_RevanRun __attribute__ ((used, section ("__DATA,__objc_const"))) = {
2,
&_OBJC_PROTOCOL_UITableViewDataSource,
&_OBJC_PROTOCOL_UITableViewDelegate
};
- 4耸彪、屬性列表
_OBJC_$_PROP_LIST_RevanPerson_$_RevanRun是一個結(jié)構(gòu)體類型,結(jié)構(gòu)體如下:
static struct /*_prop_list_t*/ {
unsigned int entsize; // sizeof(struct _prop_t)
unsigned int count_of_properties;
struct _prop_t prop_list[2];
}
當(dāng)前Category有的屬性
static struct /*_prop_list_t*/ {
unsigned int entsize; // sizeof(struct _prop_t)
unsigned int count_of_properties;
struct _prop_t prop_list[2];
} _OBJC_$_PROP_LIST_RevanPerson_$_RevanRun __attribute__ ((used, section ("__DATA,__objc_const"))) = {
sizeof(_prop_t),
2,
{{"delegate","T@\"<RevanPerson_RevanRunDelegate>\",W,N"},
{"speed","Td,N"}}
};
三忘苛、Category底層實現(xiàn)原理
- 場景:
- RevanPerson
#import <Foundation/Foundation.h>
@interface RevanPerson : NSObject
- (void)test;
@end
#import "RevanPerson.h"
@implementation RevanPerson
- (void)test {
NSLog(@"RevanPerson -test");
}
@end
- RevanPerson+RevanSleep
#import "RevanPerson.h"
@interface RevanPerson (RevanSleep)
- (void)sleep;
- (void)test;
@end
@implementation RevanPerson (RevanSleep)
- (void)sleep {
NSLog(@"RevanPerson (RevanSleep) -sleep");
}
- (void)test {
NSLog(@"RevanPerson (RevanSleep) -test");
}
@end
- 測試代碼
#import "ViewController.h"
#import "RevanPerson.h"
#import "RevanPerson+RevanRun.h"
#import "RevanPerson+RevanSleep.h"
#import <objc/runtime.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
RevanPerson *person = [[RevanPerson alloc] init];
[person test];
[person sleep];
}
@end
打印輸出:
2018-07-01 23:51:17.378727+0800 01-Category[8248:492929] RevanPerson (RevanSleep) -test
2018-07-01 23:51:17.378926+0800 01-Category[8248:492929] RevanPerson (RevanSleep) -sleep
- person對象為什么可以調(diào)用Category中的sleep方法蝉娜?
- 當(dāng)Category中有test對象方法和RevanPerson.h文件中申明的test對象方法一樣的時候,問什么會調(diào)用Category中的test扎唾?
- runtime源碼
- 分析源碼
1召川、找到_objc_init
2、找到map_images
3胸遇、找到map_images_nolock
4扮宠、找到_read_images
5、找到remethodizeClass
6狐榔、找到attachCategories
7坛增、找到attachCategories
8、找到attachLists
- 分析attachCategories函數(shù)
/**
@param cls 傳入的類
@param cats Category方法列表
*/
static void
attachCategories(Class cls, category_list *cats, bool flush_caches)
{
if (!cats) return;
if (PrintReplacedMethods) printReplacements(cls, cats);
//判斷傳入的cls是否是meta-class對象
bool isMeta = cls->isMetaClass();
// fixme rearrange to remove these intermediate allocations
// method_list_t存儲方法列表
method_list_t **mlists = (method_list_t **)
malloc(cats->count * sizeof(*mlists));
// property_list_t存儲屬性列表
property_list_t **proplists = (property_list_t **)
malloc(cats->count * sizeof(*proplists));
// protocol_list_t存儲協(xié)議列表
protocol_list_t **protolists = (protocol_list_t **)
malloc(cats->count * sizeof(*protolists));
// Count backwards through cats to get newest categories first
int mcount = 0;
int propcount = 0;
int protocount = 0;
//Category方法的個數(shù)
int i = cats->count;
bool fromBundle = NO;
while (i--) {
//倒序取出Category列表中的方法
auto& entry = cats->list[i];
//通過isMeta來判斷是去對象方法薄腻,還是類方法
method_list_t *mlist = entry.cat->methodsForMeta(isMeta);
//把Category方法倒序的添加mlists數(shù)組中
if (mlist) {
mlists[mcount++] = mlist;
fromBundle |= entry.hi->isBundle();
}
property_list_t *proplist =
entry.cat->propertiesForMeta(isMeta, entry.hi);
//把Category屬性倒序的添加proplists數(shù)組中
if (proplist) {
proplists[propcount++] = proplist;
}
protocol_list_t *protolist = entry.cat->protocols;
//把Category協(xié)議倒序的添加protolists數(shù)組中
if (protolist) {
protolists[protocount++] = protolist;
}
}
auto rw = cls->data();
prepareMethodLists(cls, mlists, mcount, NO, fromBundle);
rw->methods.attachLists(mlists, mcount);
free(mlists);
if (flush_caches && mcount > 0) flushCaches(cls);
rw->properties.attachLists(proplists, propcount);
free(proplists);
rw->protocols.attachLists(protolists, protocount);
free(protolists);
}
-
當(dāng)在沒有運行代碼時
-
當(dāng)運行代碼時
-
最后方法列表
- 小結(jié):
- 在分類和類中有相同的對象方法時收捣,因為在class對象的對象方法列表中Category中的方法排在前面
- 當(dāng)有多個Category時并且有相同方法,具體調(diào)用哪一個Category中的方法庵楷,遵守先被編譯的Category方法排在方法列表中的后面罢艾,但是一定在class對象中相同方法的前面
四楣颠、+load方法
+load方法會在runtime加載類、分類時調(diào)用咐蚯,并且每個類童漩、分類的+load在程序運行過程中只調(diào)用一次
1、一個類的+load方法和分類的+load方法調(diào)用的先后順序
- RevanPerson
#import <Foundation/Foundation.h>
@interface RevanPerson : NSObject
@end
#import "RevanPerson.h"
@implementation RevanPerson
+ (void)load {
NSLog(@"RevanPerson");
}
@end
- RevanPerson+RevanRun
#import "RevanPerson.h"
@interface RevanPerson (RevanRun)
@end
#import "RevanPerson+RevanRun.h"
@implementation RevanPerson (RevanRun)
+ (void)load {
NSLog(@"RevanPerson (RevanRun) +load");
}
@end
- RevanPerson+RevanSleep
#import "RevanPerson.h"
@interface RevanPerson (RevanSleep)
@end
#import "RevanPerson+RevanSleep.h"
@implementation RevanPerson (RevanSleep)
+(void)load {
NSLog(@"RevanPerson (RevanSleep) +load");
}
@end
- 測試代碼
#import "ViewController.h"
#import "RevanPerson.h"
#import "RevanPerson+RevanRun.h"
#import "RevanPerson+RevanSleep.h"
#import <objc/runtime.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
@end
打印輸出:
2018-07-02 02:04:49.021850+0800 01-Category[10118:587209] RevanPerson
2018-07-02 02:04:49.052238+0800 01-Category[10118:587209] RevanPerson (RevanSleep) +load
2018-07-02 02:04:49.052451+0800 01-Category[10118:587209] RevanPerson (RevanRun) +load
- 源碼分析
類和分類的+load方法是程序運行的時候就會加載春锋,所以可以查看runtime的源碼
- 1矫膨、runtime的入口void _objc_init(void)
void _objc_init(void)
{
static bool initialized = false;
if (initialized) return;
initialized = true;
// fixme defer initialization until an objc-using image is found?
environ_init();
tls_init();
static_init();
lock_init();
exception_init();
//注冊加載入口
_dyld_objc_notify_register(&map_images, load_images, unmap_image);
}
- 2、加載load鏡像load_images
void
load_images(const char *path __unused, const struct mach_header *mh)
{
// Return without taking locks if there are no +load methods here.
if (!hasLoadMethods((const headerType *)mh)) return;
recursive_mutex_locker_t lock(loadMethodLock);
// Discover load methods
{
rwlock_writer_t lock2(runtimeLock);
prepare_load_methods((const headerType *)mh);
}
//Revan:調(diào)用 +load方法
// Call +load methods (without runtimeLock - re-entrant)
call_load_methods();
}
- 3期奔、call_load_methods()加載+load方法
void call_load_methods(void)
{
static bool loading = NO;
bool more_categories;
loadMethodLock.assertLocked();
// Re-entrant calls do nothing; the outermost call will finish the job.
if (loading) return;
loading = YES;
void *pool = objc_autoreleasePoolPush();
do {
//Revan:加載class的 +load方法
// 1. Repeatedly call class +loads until there aren't any more
while (loadable_classes_used > 0) {
call_class_loads();
}
//Revan:加載Category中的 +load方法
// 2. Call category +loads ONCE
more_categories = call_category_loads();
// 3. Run more +loads if there are classes OR more untried categories
} while (loadable_classes_used > 0 || more_categories);
objc_autoreleasePoolPop(pool);
loading = NO;
}
- 調(diào)用類的+load方法call_class_loads侧馅,直接獲得程序中的所有類,并且直接執(zhí)行+load方法
static void call_class_loads(void)
{
int i;
/*
struct loadable_class {
Class cls; // may be nil
IMP method;
};
這個結(jié)構(gòu)體中的 method是load方法
*/
// Detach current loadable list.
struct loadable_class *classes = loadable_classes;
int used = loadable_classes_used;
loadable_classes = nil;
loadable_classes_allocated = 0;
loadable_classes_used = 0;
/*
loadable_classes_used是在準(zhǔn)備加載類的時候呐萌,計算出類的個數(shù)馁痴,后面具體分析
通過for循環(huán)來調(diào)用所有類的+load方法
*/
// Call all +loads for the detached list.
for (i = 0; i < used; i++) {
//獲取類
Class cls = classes[i].cls;
// typedef void(*load_method_t)(id, SEL);
//獲取方法(+load方法)
//load_method函數(shù)指針
load_method_t load_method = (load_method_t)classes[i].method;
if (!cls) continue;
if (PrintLoading) {
_objc_inform("LOAD: +[%s load]\n", cls->nameForLogging());
}
//直接執(zhí)行cls類的load方法
(*load_method)(cls, SEL_load);
}
// Destroy the detached list.
if (classes) free(classes);
}
- 4、加載分類的+load方法call_category_loads
void call_load_methods(void)
{
static bool loading = NO;
bool more_categories;
loadMethodLock.assertLocked();
// Re-entrant calls do nothing; the outermost call will finish the job.
if (loading) return;
loading = YES;
void *pool = objc_autoreleasePoolPush();
do {
//Revan:加載class的 +load方法
// 1. Repeatedly call class +loads until there aren't any more
while (loadable_classes_used > 0) {
call_class_loads();
}
/********** 加載類的+load方法都完成后接下來才加載分類的+load方法 ***********/
//Revan:加載Category中的 +load方法
// 2. Call category +loads ONCE
more_categories = call_category_loads();
// 3. Run more +loads if there are classes OR more untried categories
} while (loadable_classes_used > 0 || more_categories);
objc_autoreleasePoolPop(pool);
loading = NO;
}
- 調(diào)用分類的+load方法(call_category_loads)
static bool call_category_loads(void)
{
int i, shift;
bool new_categories_added = NO;
/**
struct loadable_category {
Category cat; // may be nil
IMP method;
};
*/
// Detach current loadable list.
struct loadable_category *cats = loadable_categories;
int used = loadable_categories_used;
int allocated = loadable_categories_allocated;
loadable_categories = nil;
loadable_categories_allocated = 0;
loadable_categories_used = 0;
// Call all +loads for the detached list.
for (i = 0; i < used; i++) {
//typedef struct category_t *Category;
//獲取分類
Category cat = cats[i].cat;
//獲取分類中的+load方法
load_method_t load_method = (load_method_t)cats[i].method;
Class cls;
if (!cat) continue;
cls = _category_getClass(cat);
if (cls && cls->isLoadable()) {
if (PrintLoading) {
_objc_inform("LOAD: +[%s(%s) load]\n",
cls->nameForLogging(),
_category_getName(cat));
}
//執(zhí)行類的+load方法
(*load_method)(cls, SEL_load);
cats[i].cat = nil;
}
}
// Compact detached list (order-preserving)
shift = 0;
for (i = 0; i < used; i++) {
if (cats[i].cat) {
cats[i-shift] = cats[i];
} else {
shift++;
}
}
used -= shift;
// Copy any new +load candidates from the new list to the detached list.
new_categories_added = (loadable_categories_used > 0);
for (i = 0; i < loadable_categories_used; i++) {
if (used == allocated) {
allocated = allocated*2 + 16;
cats = (struct loadable_category *)
realloc(cats, allocated *
sizeof(struct loadable_category));
}
cats[used++] = loadable_categories[i];
}
// Destroy the new list.
if (loadable_categories) free(loadable_categories);
// Reattach the (now augmented) detached list.
// But if there's nothing left to load, destroy the list.
if (used) {
loadable_categories = cats;
loadable_categories_used = used;
loadable_categories_allocated = allocated;
} else {
if (cats) free(cats);
loadable_categories = nil;
loadable_categories_used = 0;
loadable_categories_allocated = 0;
}
if (PrintLoading) {
if (loadable_categories_used != 0) {
_objc_inform("LOAD: %d categories still waiting for +load\n",
loadable_categories_used);
}
}
return new_categories_added;
}
- 小結(jié):
- 從上面的分析可以很肯定的一點是肺孤,在類和分類同時存在的情況下罗晕,肯定是先執(zhí)行類的+load方法之后才執(zhí)行分類的+load方法
2、多個類的+load方法調(diào)用順序
- RevanPerson類
#import <Foundation/Foundation.h>
@interface RevanPerson : NSObject
@end
#import "RevanPerson.h"
@implementation RevanPerson
+ (void)load {
NSLog(@"RevanPerson +load");
}
@end
- RevanCat類
#import <Foundation/Foundation.h>
@interface RevanCat : NSObject
@end
#import "RevanCat.h"
@implementation RevanCat
+ (void)load {
NSLog(@"RevanCat +load");
}
@end
- RevanCar類
#import <Foundation/Foundation.h>
@interface RevanCar : NSObject
@end
#import "RevanCar.h"
@implementation RevanCar
+ (void)load {
NSLog(@"RevanCar +load");
}
@end
-
編譯順序
輸出打印
2018-07-02 21:43:02.233461+0800 03-moreClassload[11450:679953] RevanCat +load
2018-07-02 21:43:02.234868+0800 03-moreClassload[11450:679953] RevanPerson +load
2018-07-02 21:43:02.235437+0800 03-moreClassload[11450:679953] RevanCar +load
-
調(diào)整編譯順序
- 輸出打釉隆:
2018-07-02 21:47:21.731838+0800 03-moreClassload[11502:683412] RevanCar +load
2018-07-02 21:47:21.743166+0800 03-moreClassload[11502:683412] RevanCat +load
2018-07-02 21:47:21.744275+0800 03-moreClassload[11502:683412] RevanPerson +load
- 源碼分析
- 1小渊、runtime初始化的方法
void _objc_init(void)
{
static bool initialized = false;
if (initialized) return;
initialized = true;
// fixme defer initialization until an objc-using image is found?
environ_init();
tls_init();
static_init();
lock_init();
exception_init();
//注冊加載入口
_dyld_objc_notify_register(&map_images, load_images, unmap_image);
}
- 2、加載load的鏡像方法
void
load_images(const char *path __unused, const struct mach_header *mh)
{
// Return without taking locks if there are no +load methods here.
if (!hasLoadMethods((const headerType *)mh)) return;
recursive_mutex_locker_t lock(loadMethodLock);
// Discover load methods
{
rwlock_writer_t lock2(runtimeLock);
//準(zhǔn)備加載load方法
prepare_load_methods((const headerType *)mh);
}
//Revan:調(diào)用 +load方法
// Call +load methods (without runtimeLock - re-entrant)
call_load_methods();
}
- 3顾腊、剛才分析加載load方法(call_load_methods)粤铭,在里面我們看到了存儲類和分類的數(shù)組挖胃,那么這個數(shù)組中的值是什么時候加載的呢杂靶?從上面的源碼可以發(fā)現(xiàn)在加載call_load_methods函數(shù)的前面有一個準(zhǔn)備加載load方法的函數(shù)prepare_load_methods函數(shù)
void prepare_load_methods(const headerType *mhdr)
{
size_t count, i;
runtimeLock.assertWriting();
//_getObjc2NonlazyClassList:獲取objc不是懶加載類的列表
//這個方法應(yīng)該是獲得程序中所有的類
//typedef struct classref * classref_t;
classref_t *classlist =
_getObjc2NonlazyClassList(mhdr, &count);
//通過遍歷存儲類的數(shù)組,
for (i = 0; i < count; i++) {
/*
把類傳入到定制加載類的load函數(shù)中(schedule_class_load)
如果傳入的是一個子類酱鸭,那么他會一層一層取到cls的父類
然后在一個一個的把類添加到一個數(shù)組中(add_class_to_loadable_list函數(shù)實現(xiàn))
*/
schedule_class_load(remapClass(classlist[i]));
}
//_getObjc2NonlazyCategoryList:獲取objc不是懶加載分類的列表
category_t **categorylist = _getObjc2NonlazyCategoryList(mhdr, &count);
for (i = 0; i < count; i++) {
//獲取分類category_t
category_t *cat = categorylist[i];
//把category_t轉(zhuǎn)化成類
Class cls = remapClass(cat->cls);
if (!cls) continue; // category for ignored weak-linked class
realizeClass(cls);
assert(cls->ISA()->isRealized());
//獲取分類數(shù)組
add_category_to_loadable_list(cat);
}
}
- 4吗垮、加載類的load方法做一些schedule事情(schedule_class_load):比如查找類的父類
static void schedule_class_load(Class cls)
{
if (!cls) return;
assert(cls->isRealized()); // _read_images should realize
if (cls->data()->flags & RW_LOADED) return;
// Ensure superclass-first ordering
/*
這是一個遞歸,
先獲得傳入的類的父類
之后在傳入定制加載類的+load方法
*/
schedule_class_load(cls->superclass);
//把類一個一個的添加到數(shù)組中
add_class_to_loadable_list(cls);
cls->setInfo(RW_LOADED);
}
- 5凹髓、使用add_class_to_loadable_list函數(shù)把類加載到一個數(shù)組loadable_classes中
void add_class_to_loadable_list(Class cls)
{
IMP method;
loadMethodLock.assertLocked();
//獲取類的load方法
method = cls->getLoadMethod();
if (!method) return; // Don't bother if cls has no +load method
if (PrintLoading) {
_objc_inform("LOAD: class '%s' scheduled for +load",
cls->nameForLogging());
}
/**
最開始
static int loadable_classes_used = 0;
static int loadable_classes_allocated = 0;
所以第一次會進(jìn)入if判斷中
loadable_classes_allocated = 16
在執(zhí)行了call_class_loads函數(shù)后:
loadable_classes_allocated = 0;
loadable_classes_used = 0;
*/
if (loadable_classes_used == loadable_classes_allocated) {
loadable_classes_allocated = loadable_classes_allocated*2 + 16;
//給loadable_classes數(shù)組分配空間
loadable_classes = (struct loadable_class *)
realloc(loadable_classes,
loadable_classes_allocated *
sizeof(struct loadable_class));
}
//獲取loadable_classes_used元素并且給屬性賦值(cls烁登、method)
loadable_classes[loadable_classes_used].cls = cls;
loadable_classes[loadable_classes_used].method = method;
//下標(biāo)++
loadable_classes_used++;
}
- 小結(jié):
- 可以肯定的是在有多個類的時候,加載類的+load方法的先后順序是要看這些類的編譯順的蔚舀,先編譯先調(diào)用類的load方法
4饵沧、一個類和子類的+load方法調(diào)用順序
- RevanPerson
#import <Foundation/Foundation.h>
@interface RevanPerson : NSObject
@end
#import "RevanPerson.h"
@implementation RevanPerson
+ (void)load {
NSLog(@"RevanPerson");
}
@end
- RevanStudent
#import "RevanPerson.h"
@interface RevanStudent : RevanPerson
@end
#import "RevanStudent.h"
@implementation RevanStudent
+ (void)load {
NSLog(@"RevanStudent");
}
@end
- 測試代碼
#import "ViewController.h"
#import "RevanPerson.h"
#import "RevanPerson+RevanRun.h"
#import "RevanPerson+RevanSleep.h"
#import <objc/runtime.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
@end
打印輸出:
2018-07-02 02:07:36.637509+0800 01-Category[10168:589605] RevanPerson
2018-07-02 02:07:36.639657+0800 01-Category[10168:589605] RevanStudent
- 小結(jié):
- 通過上面的源碼分析,我們可以知道赌躺,在準(zhǔn)備加載類的load方法中有一個schedule_class_load函數(shù)狼牺,在這個函數(shù)中會遞歸調(diào)用schedule_class_load函數(shù)傳入父類,然后再調(diào)用add_class_to_loadable_list函數(shù)把類一個一個追加到數(shù)組loadable_classes中礼患,由于在使用數(shù)組loadable_classes的時候是用的for循環(huán)是钥,從前往后一個一個取值掠归,所以會先調(diào)用父類的load方法再調(diào)用子類的load方法。
- 源碼輔助理解
//定制化class的load函數(shù)
static void schedule_class_load(Class cls)
{
if (!cls) return;
assert(cls->isRealized()); // _read_images should realize
if (cls->data()->flags & RW_LOADED) return;
// Ensure superclass-first ordering
/*
這是一個遞歸悄泥,
先獲得傳入的類的父類
之后在傳入定制加載類的+load方法
*/
schedule_class_load(cls->superclass);
//把類一個一個的添加到數(shù)組中
add_class_to_loadable_list(cls);
cls->setInfo(RW_LOADED);
}
//把類加入到loadable_classes數(shù)組中
void add_class_to_loadable_list(Class cls)
{
IMP method;
loadMethodLock.assertLocked();
//獲取類的load方法
method = cls->getLoadMethod();
if (!method) return; // Don't bother if cls has no +load method
if (PrintLoading) {
_objc_inform("LOAD: class '%s' scheduled for +load",
cls->nameForLogging());
}
/**
最開始
static int loadable_classes_used = 0;
static int loadable_classes_allocated = 0;
所以第一次會進(jìn)入if判斷中
loadable_classes_allocated = 16
在執(zhí)行了call_class_loads函數(shù)后:
loadable_classes_allocated = 0;
loadable_classes_used = 0;
*/
if (loadable_classes_used == loadable_classes_allocated) {
loadable_classes_allocated = loadable_classes_allocated*2 + 16;
//給loadable_classes數(shù)組分配空間
loadable_classes = (struct loadable_class *)
realloc(loadable_classes,
loadable_classes_allocated *
sizeof(struct loadable_class));
}
//獲取loadable_classes_used元素并且給屬性賦值(cls虏冻、method)
loadable_classes[loadable_classes_used].cls = cls;
loadable_classes[loadable_classes_used].method = method;
//下標(biāo)++
loadable_classes_used++;
}
5、當(dāng)類有Category并且子類也有Category的時候+load調(diào)用順序
- RevanPerson
#import <Foundation/Foundation.h>
@interface RevanPerson : NSObject
@end
#import "RevanPerson.h"
@implementation RevanPerson
+ (void)load {
NSLog(@"RevanPerson");
}
@end
- RevanPerson+RevanRun
#import "RevanPerson.h"
@interface RevanPerson (RevanRun)
@end
#import "RevanPerson+RevanRun.h"
@implementation RevanPerson (RevanRun)
+ (void)load {
NSLog(@"RevanPerson (RevanRun) +load");
}
@end
- RevanPerson+RevanSleep
#import "RevanPerson.h"
@interface RevanPerson (RevanSleep)
@end
#import "RevanPerson+RevanSleep.h"
@implementation RevanPerson (RevanSleep)
+(void)load {
NSLog(@"RevanPerson (RevanSleep) +load");
}
@end
- RevanStudent
#import "RevanPerson.h"
@interface RevanStudent : RevanPerson
@end
#import "RevanStudent.h"
@implementation RevanStudent
+ (void)load {
NSLog(@"RevanStudent");
}
@end
- RevanStudent+RevanRun
#import "RevanStudent.h"
@interface RevanStudent (RevanRun)
@end
#import "RevanStudent+RevanRun.h"
@implementation RevanStudent (RevanRun)
+ (void)load {
NSLog(@"RevanStudent (RevanRun) +load");
}
@end
- 測試代碼
#import "ViewController.h"
#import "RevanPerson.h"
#import "RevanPerson+RevanRun.h"
#import "RevanPerson+RevanSleep.h"
#import <objc/runtime.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
@end
打印輸出:
2018-07-02 02:12:04.902102+0800 01-Category[10233:593298] RevanPerson
2018-07-02 02:12:04.905031+0800 01-Category[10233:593298] RevanStudent
2018-07-02 02:12:04.906406+0800 01-Category[10233:593298] RevanStudent (RevanRun) +load
2018-07-02 02:12:04.907060+0800 01-Category[10233:593298] RevanPerson (RevanSleep) +load
2018-07-02 02:12:04.908733+0800 01-Category[10233:593298] RevanPerson (RevanRun) +load
5弹囚、加載+load方法的源碼分析
- runtime入口
void _objc_init(void)
{
static bool initialized = false;
if (initialized) return;
initialized = true;
// fixme defer initialization until an objc-using image is found?
environ_init();
tls_init();
static_init();
lock_init();
exception_init();
//注冊加載入口
_dyld_objc_notify_register(&map_images, load_images, unmap_image);
}
- 加載load鏡像
load_images(const char *path __unused, const struct mach_header *mh)
{
// Return without taking locks if there are no +load methods here.
if (!hasLoadMethods((const headerType *)mh)) return;
recursive_mutex_locker_t lock(loadMethodLock);
// Discover load methods
{
rwlock_writer_t lock2(runtimeLock);
//準(zhǔn)備加載load方法
prepare_load_methods((const headerType *)mh);
}
//Revan:調(diào)用 +load方法
// Call +load methods (without runtimeLock - re-entrant)
call_load_methods();
}
- 5.1厨相、runtime加載代碼中有多少個類的
- 5.1.1、準(zhǔn)備加載load方法(prepare_load_methods)余寥,在里面有些注釋领铐。在獲取類的load方法和獲取分類的load方法大致是一樣的,唯一不一樣的地方是在遍歷獲取類的load中是調(diào)用了一個加載類的load方法的定制函數(shù)(schedule_class_load函數(shù))宋舷,這個函數(shù)中自己調(diào)用自己绪撵,傳入的參數(shù)是父類,通過遞歸來獲得父類祝蝠,最后在執(zhí)行add_class_to_loadable_list來把類的load方法都添加到loadable_classes數(shù)組中音诈;添加分類的load方法是沒有遞歸父類的load方法這一步,直接使用add_category_to_loadable_list函數(shù)添加分類的load方法到loadable_categories數(shù)組中
void prepare_load_methods(const headerType *mhdr)
{
size_t count, i;
runtimeLock.assertWriting();
//_getObjc2NonlazyClassList:獲取objc不是懶加載類的列表
//這個方法應(yīng)該是獲得程序中所有的類
//typedef struct classref * classref_t;
classref_t *classlist =
_getObjc2NonlazyClassList(mhdr, &count);
//通過遍歷存儲類的數(shù)組绎狭,
for (i = 0; i < count; i++) {
/*
把類傳入到定制加載類的load函數(shù)中(schedule_class_load)
如果傳入的是一個子類细溅,那么他會一層一層取到cls的父類
然后在一個一個的把類添加到一個數(shù)組中(add_class_to_loadable_list函數(shù)實現(xiàn))
*/
schedule_class_load(remapClass(classlist[i]));
}
//_getObjc2NonlazyCategoryList:獲取objc不是懶加載分類的列表
category_t **categorylist = _getObjc2NonlazyCategoryList(mhdr, &count);
for (i = 0; i < count; i++) {
//獲取分類category_t
category_t *cat = categorylist[i];
//把category_t轉(zhuǎn)化成類
Class cls = remapClass(cat->cls);
if (!cls) continue; // category for ignored weak-linked class
realizeClass(cls);
assert(cls->ISA()->isRealized());
//獲取分類數(shù)組
add_category_to_loadable_list(cat);
}
}
- 類的load方法schedule函數(shù)schedule_class_load
static void schedule_class_load(Class cls)
{
if (!cls) return;
assert(cls->isRealized()); // _read_images should realize
if (cls->data()->flags & RW_LOADED) return;
// Ensure superclass-first ordering
/*
這是一個遞歸,
先獲得傳入的類的父類
之后在傳入定制加載類的+load方法
*/
schedule_class_load(cls->superclass);
//把類一個一個的添加到數(shù)組中
add_class_to_loadable_list(cls);
cls->setInfo(RW_LOADED);
}
- 把類的load方法添加到loadable_classes數(shù)組中
void add_class_to_loadable_list(Class cls)
{
IMP method;
loadMethodLock.assertLocked();
//獲取類的load方法
method = cls->getLoadMethod();
if (!method) return; // Don't bother if cls has no +load method
if (PrintLoading) {
_objc_inform("LOAD: class '%s' scheduled for +load",
cls->nameForLogging());
}
/**
最開始
static int loadable_classes_used = 0;
static int loadable_classes_allocated = 0;
所以第一次會進(jìn)入if判斷中
loadable_classes_allocated = 16
在執(zhí)行了call_class_loads函數(shù)后:
loadable_classes_allocated = 0;
loadable_classes_used = 0;
*/
if (loadable_classes_used == loadable_classes_allocated) {
loadable_classes_allocated = loadable_classes_allocated*2 + 16;
//給loadable_classes數(shù)組分配空間
loadable_classes = (struct loadable_class *)
realloc(loadable_classes,
loadable_classes_allocated *
sizeof(struct loadable_class));
}
//獲取loadable_classes_used元素并且給屬性賦值(cls儡嘶、method)
loadable_classes[loadable_classes_used].cls = cls;
loadable_classes[loadable_classes_used].method = method;
//下標(biāo)++
loadable_classes_used++;
}
- 添加分類的load方法到loadable_categories數(shù)組中
void add_category_to_loadable_list(Category cat)
{
IMP method;
loadMethodLock.assertLocked();
method = _category_getLoadMethod(cat);
// Don't bother if cat has no +load method
if (!method) return;
if (PrintLoading) {
_objc_inform("LOAD: category '%s(%s)' scheduled for +load",
_category_getClassName(cat), _category_getName(cat));
}
if (loadable_categories_used == loadable_categories_allocated) {
loadable_categories_allocated = loadable_categories_allocated*2 + 16;
loadable_categories = (struct loadable_category *)
realloc(loadable_categories,
loadable_categories_allocated *
sizeof(struct loadable_category));
}
loadable_categories[loadable_categories_used].cat = cat;
loadable_categories[loadable_categories_used].method = method;
loadable_categories_used++;
}
- 5.2喇聊、runtime調(diào)用類或者分類的load方法
- 5.2.1、call_load_methods函數(shù)蹦狂,通過loadable_classes_used來判斷是否有類誓篱,如何有就調(diào)用類的call_class_loads函數(shù)
void call_load_methods(void)
{
static bool loading = NO;
bool more_categories;
loadMethodLock.assertLocked();
// Re-entrant calls do nothing; the outermost call will finish the job.
if (loading) return;
loading = YES;
void *pool = objc_autoreleasePoolPush();
do {
//Revan:加載class的 +load方法
// 1. Repeatedly call class +loads until there aren't any more
while (loadable_classes_used > 0) {
call_class_loads();
}
/********** 加載類的+load方法都完成后接下來才加載分類的+load方法 ***********/
//Revan:加載Category中的 +load方法
// 2. Call category +loads ONCE
more_categories = call_category_loads();
// 3. Run more +loads if there are classes OR more untried categories
} while (loadable_classes_used > 0 || more_categories);
objc_autoreleasePoolPop(pool);
loading = NO;
}
- 5.2.2、調(diào)用觸發(fā)(類調(diào)用load方法的函數(shù)(call_class_loads))在這里存儲類的數(shù)組classes凯楔,遍歷數(shù)組classes窜骄,直接拿到method中的load方法直接執(zhí)行。所以call_class_loads函數(shù)調(diào)用過后類的load方法都已經(jīng)調(diào)用完成
static void call_class_loads(void)
{
int i;
/*
struct loadable_class {
Class cls; // may be nil
IMP method;
};
這個結(jié)構(gòu)體中的 method是load方法
*/
// Detach current loadable list.
struct loadable_class *classes = loadable_classes;
int used = loadable_classes_used;
loadable_classes = nil;
loadable_classes_allocated = 0;
loadable_classes_used = 0;
/*
loadable_classes_used是在準(zhǔn)備加載類的時候摆屯,計算出類的個數(shù)邻遏,后面具體分析
通過for循環(huán)來調(diào)用所有類的+load方法
*/
// Call all +loads for the detached list.
for (i = 0; i < used; i++) {
//獲取類
Class cls = classes[i].cls;
// typedef void(*load_method_t)(id, SEL);
//獲取方法(+load方法)
//load_method函數(shù)指針
load_method_t load_method = (load_method_t)classes[i].method;
if (!cls) continue;
if (PrintLoading) {
_objc_inform("LOAD: +[%s load]\n", cls->nameForLogging());
}
//直接執(zhí)行cls類的load方法
(*load_method)(cls, SEL_load);
}
// Destroy the detached list.
if (classes) free(classes);
}
- 5.2.3、觸發(fā)(分類調(diào)用load函數(shù)(call_category_loads))拿到存儲分類的loadable_categories數(shù)組虐骑,通過遍歷數(shù)組loadable_categories准验,來獲得method和轉(zhuǎn)換的cls,之后直接調(diào)用
static bool call_category_loads(void)
{
int i, shift;
bool new_categories_added = NO;
/**
struct loadable_category {
Category cat; // may be nil
IMP method;
};
*/
// Detach current loadable list.
struct loadable_category *cats = loadable_categories;
int used = loadable_categories_used;
int allocated = loadable_categories_allocated;
loadable_categories = nil;
loadable_categories_allocated = 0;
loadable_categories_used = 0;
// Call all +loads for the detached list.
for (i = 0; i < used; i++) {
//typedef struct category_t *Category;
//獲取分類
Category cat = cats[i].cat;
//獲取分類中的+load方法
load_method_t load_method = (load_method_t)cats[i].method;
Class cls;
if (!cat) continue;
cls = _category_getClass(cat);
if (cls && cls->isLoadable()) {
if (PrintLoading) {
_objc_inform("LOAD: +[%s(%s) load]\n",
cls->nameForLogging(),
_category_getName(cat));
}
//執(zhí)行類的+load方法
(*load_method)(cls, SEL_load);
cats[i].cat = nil;
}
}
// Compact detached list (order-preserving)
shift = 0;
for (i = 0; i < used; i++) {
if (cats[i].cat) {
cats[i-shift] = cats[i];
} else {
shift++;
}
}
used -= shift;
// Copy any new +load candidates from the new list to the detached list.
new_categories_added = (loadable_categories_used > 0);
for (i = 0; i < loadable_categories_used; i++) {
if (used == allocated) {
allocated = allocated*2 + 16;
cats = (struct loadable_category *)
realloc(cats, allocated *
sizeof(struct loadable_category));
}
cats[used++] = loadable_categories[i];
}
// Destroy the new list.
if (loadable_categories) free(loadable_categories);
// Reattach the (now augmented) detached list.
// But if there's nothing left to load, destroy the list.
if (used) {
loadable_categories = cats;
loadable_categories_used = used;
loadable_categories_allocated = allocated;
} else {
if (cats) free(cats);
loadable_categories = nil;
loadable_categories_used = 0;
loadable_categories_allocated = 0;
}
if (PrintLoading) {
if (loadable_categories_used != 0) {
_objc_inform("LOAD: %d categories still waiting for +load\n",
loadable_categories_used);
}
}
return new_categories_added;
}
- 小結(jié)
- a)調(diào)用類的+load方法
- 先調(diào)用類的+load方法廷没,按照編譯先后順序調(diào)用(先編譯糊饱,先調(diào)用)
- 調(diào)用子類的+load之前會先調(diào)用父類的+load方法
- b)調(diào)用分類的+load方法
- 按照編譯先后順序調(diào)用(先編譯,先調(diào)用)
- a)調(diào)用類的+load方法
五腕柜、+initialize方法
+initialize方法會在類第一次接收到消息時調(diào)用
- RevanPerson
#import <Foundation/Foundation.h>
@interface RevanPerson : NSObject
@end
#import "RevanPerson.h"
@implementation RevanPerson
+ (void)initialize {
NSLog(@"RevanPerson + initialize");
}
@end
- 測試代碼
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
@end
- 沒有輸出济似,RevanPerson中的initialize方法沒有調(diào)用矫废,所以當(dāng)代碼中不使用RevanPerson這個類的時候,是不會觸發(fā)initialize方法
- 測試代碼(使用RevanPerson)
#import "ViewController.h"
#import "RevanPerson.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[RevanPerson alloc];
}
@end
- 打印輸出:2018-07-03 01:47:32.869743+0800 04-initialize[13794:849444] RevanPerson + initialize
1砰蠢、但類和分類中都有+ initialize方法時蓖扑,initialize如何調(diào)用
- 1、RevanPerson
#import <Foundation/Foundation.h>
@interface RevanPerson : NSObject
@end
#import "RevanPerson.h"
@implementation RevanPerson
+ (void)initialize {
NSLog(@"RevanPerson + initialize");
}
@end
- 2台舱、RevanPerson+RevanRun
#import "RevanPerson.h"
@interface RevanPerson (RevanRun)
@end
#import "RevanPerson+RevanRun.h"
@implementation RevanPerson (RevanRun)
+ (void)initialize {
NSLog(@"RevanPerson (RevanRun) + initialize");
}
@end
- 3律杠、RevanPerson+RevanEat
#import "RevanPerson.h"
@interface RevanPerson (RevanEat)
@end
#import "RevanPerson+RevanEat.h"
@implementation RevanPerson (RevanEat)
+ (void)initialize {
NSLog(@"RevanPerson (RevanEat) + initialize");
}
@end
- 測試代碼
#import "ViewController.h"
#import "RevanPerson.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[RevanPerson alloc];
}
@end
打印輸出:
2018-07-03 01:54:59.108693+0800 04-initialize[13882:854989] RevanPerson (RevanEat) + initialize
- 發(fā)現(xiàn)是使用的分類中的+initialize方法。調(diào)整2個分類的編譯順序后竞惋,發(fā)現(xiàn)打印結(jié)果發(fā)生改變
2018-07-03 01:56:12.115167+0800 04-initialize[13899:856044] RevanPerson (RevanRun) + initialize
- 4柜去、源碼分析
- 4.1、找到objc-runtime-new.mm文件中的class_getInstanceMethod
Method class_getInstanceMethod(Class cls, SEL sel)
{
if (!cls || !sel) return nil;
// This deliberately avoids +initialize because it historically did so.
// This implementation is a bit weird because it's the only place that
// wants a Method instead of an IMP.
#warning fixme build and search caches
// Search method lists, try method resolver, etc.
lookUpImpOrNil(cls, sel, nil,
NO/*initialize*/, NO/*cache*/, YES/*resolver*/);
#warning fixme build and search caches
return _class_getMethod(cls, sel);
}
- 4.2拆宛、查看lookUpImpOrNil方法
IMP lookUpImpOrNil(Class cls, SEL sel, id inst,
bool initialize, bool cache, bool resolver)
{
IMP imp = lookUpImpOrForward(cls, sel, inst, initialize, cache, resolver);
if (imp == _objc_msgForward_impcache) return nil;
else return imp;
}
- 4.3嗓奢、查看lookUpImpOrForward函數(shù)
IMP lookUpImpOrForward(Class cls, SEL sel, id inst,
bool initialize, bool cache, bool resolver)
{
IMP imp = nil;
bool triedResolver = NO;
runtimeLock.assertUnlocked();
// Optimistic cache lookup
if (cache) {
imp = cache_getImp(cls, sel);
if (imp) return imp;
}
// runtimeLock is held during isRealized and isInitialized checking
// to prevent races against concurrent realization.
// runtimeLock is held during method search to make
// method-lookup + cache-fill atomic with respect to method addition.
// Otherwise, a category could be added but ignored indefinitely because
// the cache was re-filled with the old value after the cache flush on
// behalf of the category.
runtimeLock.read();
if (!cls->isRealized()) {
// Drop the read-lock and acquire the write-lock.
// realizeClass() checks isRealized() again to prevent
// a race while the lock is down.
runtimeLock.unlockRead();
runtimeLock.write();
realizeClass(cls);
runtimeLock.unlockWrite();
runtimeLock.read();
}
/*
initialize:是否需要初始化
isInitialized函數(shù)判斷cls類是否已經(jīng)初始化
當(dāng)initialize = YES
isInitialized返回為NO
*/
if (initialize && !cls->isInitialized()) {
runtimeLock.unlockRead();
_class_initialize (_class_getNonMetaClass(cls, inst));
runtimeLock.read();
// If sel == initialize, _class_initialize will send +initialize and
// then the messenger will send +initialize again after this
// procedure finishes. Of course, if this is not being called
// from the messenger then it won't happen. 2778172
}
retry:
runtimeLock.assertReading();
// Try this class's cache.
imp = cache_getImp(cls, sel);
if (imp) goto done;
// Try this class's method lists.
{
Method meth = getMethodNoSuper_nolock(cls, sel);
if (meth) {
log_and_fill_cache(cls, meth->imp, sel, inst, cls);
imp = meth->imp;
goto done;
}
}
// Try superclass caches and method lists.
{
unsigned attempts = unreasonableClassCount();
for (Class curClass = cls->superclass;
curClass != nil;
curClass = curClass->superclass)
{
// Halt if there is a cycle in the superclass chain.
if (--attempts == 0) {
_objc_fatal("Memory corruption in class list.");
}
// Superclass cache.
imp = cache_getImp(curClass, sel);
if (imp) {
if (imp != (IMP)_objc_msgForward_impcache) {
// Found the method in a superclass. Cache it in this class.
log_and_fill_cache(cls, imp, sel, inst, curClass);
goto done;
}
else {
// Found a forward:: entry in a superclass.
// Stop searching, but don't cache yet; call method
// resolver for this class first.
break;
}
}
// Superclass method list.
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
imp = meth->imp;
goto done;
}
}
}
// No implementation found. Try method resolver once.
if (resolver && !triedResolver) {
runtimeLock.unlockRead();
_class_resolveMethod(cls, sel, inst);
runtimeLock.read();
// Don't cache the result; we don't hold the lock so it may have
// changed already. Re-do the search from scratch instead.
triedResolver = YES;
goto retry;
}
// No implementation found, and method resolver didn't help.
// Use forwarding.
imp = (IMP)_objc_msgForward_impcache;
cache_fill(cls, sel, imp, inst);
done:
runtimeLock.unlockRead();
return imp;
}
- 4.4、通過傳入的參數(shù)initialize和調(diào)用類的isInitialized函數(shù)的返回結(jié)果一起來判斷是否調(diào)用_class_initialize函數(shù)浑厚,是否要初始化類股耽;當(dāng)這個類需要初始化(initialize=YES)并且還沒有初始化(isInitialized函數(shù)返回值為NO時)會調(diào)用_class_initialize函數(shù)進(jìn)行初始化。
- 4.4.1钳幅、首先會找到cls的父類物蝙,查看父類是否存在,父類是否已經(jīng)初始化敢艰,當(dāng)父類也需要初始化的時候會遞歸調(diào)用_class_initialize函數(shù)
- 4.4.2诬乞、在父類初始化完成以后,如果當(dāng)前類沒有初始化钠导,那么進(jìn)行當(dāng)前類的初始化并且把reallyInitialize=YES
- 4.4.3震嫉、當(dāng)前類已經(jīng)初始化完成后調(diào)用callInitialize函數(shù)
void _class_initialize(Class cls)
{
assert(!cls->isMetaClass());
Class supercls;
bool reallyInitialize = NO;
// Make sure super is done initializing BEFORE beginning to initialize cls.
// See note about deadlock above.
//獲得父類
supercls = cls->superclass;
//存在父類對象并且父類沒有初始化,執(zhí)行遞歸初始化方法辈双,給父類初始化
if (supercls && !supercls->isInitialized()) {
_class_initialize(supercls);
}
// Try to atomically set CLS_INITIALIZING.
{
monitor_locker_t lock(classInitLock);
//如果傳進(jìn)來的類沒有初始化责掏,就給類初始化并且reallyInitialize設(shè)置為YES
if (!cls->isInitialized() && !cls->isInitializing()) {
cls->setInitializing();
reallyInitialize = YES;
}
}
///已經(jīng)初始化了
if (reallyInitialize) {
// We successfully set the CLS_INITIALIZING bit. Initialize the class.
// Record that we're initializing this class so we can message it.
_setThisThreadIsInitializingClass(cls);
if (MultithreadedForkChild) {
// LOL JK we don't really call +initialize methods after fork().
performForkChildInitialize(cls, supercls);
return;
}
// Send the +initialize message.
// Note that +initialize is sent to the superclass (again) if
// this class doesn't implement +initialize. 2157218
if (PrintInitializing) {
_objc_inform("INITIALIZE: thread %p: calling +[%s initialize]",
pthread_self(), cls->nameForLogging());
}
// Exceptions: A +initialize call that throws an exception
// is deemed to be a complete and successful +initialize.
//
// Only __OBJC2__ adds these handlers. !__OBJC2__ has a
// bootstrapping problem of this versus CF's call to
// objc_exception_set_functions().
#if __OBJC2__
@try
#endif
{
//調(diào)用類的初始化方法柜砾,是在給類cls發(fā)送一個SEL_initialize消息
callInitialize(cls);
if (PrintInitializing) {
_objc_inform("INITIALIZE: thread %p: finished +[%s initialize]",
pthread_self(), cls->nameForLogging());
}
}
#if __OBJC2__
@catch (...) {
if (PrintInitializing) {
_objc_inform("INITIALIZE: thread %p: +[%s initialize] "
"threw an exception",
pthread_self(), cls->nameForLogging());
}
@throw;
}
@finally
#endif
{
// Done initializing.
lockAndFinishInitializing(cls, supercls);
}
return;
}
else if (cls->isInitializing()) {
// We couldn't set INITIALIZING because INITIALIZING was already set.
// If this thread set it earlier, continue normally.
// If some other thread set it, block until initialize is done.
// It's ok if INITIALIZING changes to INITIALIZED while we're here,
// because we safely check for INITIALIZED inside the lock
// before blocking.
if (_thisThreadIsInitializingClass(cls)) {
return;
} else if (!MultithreadedForkChild) {
waitForInitializeToComplete(cls);
return;
} else {
// We're on the child side of fork(), facing a class that
// was initializing by some other thread when fork() was called.
_setThisThreadIsInitializingClass(cls);
performForkChildInitialize(cls, supercls);
}
}
else if (cls->isInitialized()) {
// Set CLS_INITIALIZING failed because someone else already
// initialized the class. Continue normally.
// NOTE this check must come AFTER the ISINITIALIZING case.
// Otherwise: Another thread is initializing this class. ISINITIALIZED
// is false. Skip this clause. Then the other thread finishes
// initialization and sets INITIALIZING=no and INITIALIZED=yes.
// Skip the ISINITIALIZING clause. Die horribly.
return;
}
else {
// We shouldn't be here.
_objc_fatal("thread-safe class init in objc runtime is buggy!");
}
}
- 4.5湃望、調(diào)用初始化callInitialize,實質(zhì)是給當(dāng)前類發(fā)送一個SEL_initialize消息
/**
調(diào)用初始化方法(給類發(fā)送SEL_initialize初始化消息)
@param cls 類
*/
void callInitialize(Class cls)
{
((void(*)(Class, SEL))objc_msgSend)(cls, SEL_initialize);
asm("");
}
- 小結(jié)
- 調(diào)用+initialize本質(zhì)是給一個類發(fā)送一個initialize消息痰驱,由于消息機(jī)制的本質(zhì)(isa指針证芭、supercla指針),所以會優(yōu)先調(diào)用分類的方法
2担映、類和子類都有+initialize
- 父類RevanPerson
#import <Foundation/Foundation.h>
@interface RevanPerson : NSObject
@end
#import "RevanPerson.h"
@implementation RevanPerson
+ (void)initialize {
NSLog(@"RevanPerson + initialize");
}
@end
- 子類RevanStudent
#import "RevanPerson.h"
@interface RevanStudent : RevanPerson
@end
#import "RevanStudent.h"
@implementation RevanStudent
+ (void)initialize {
NSLog(@"RevanStudent + initialize");
}
@end
- 測試代碼
#import "ViewController.h"
#import "RevanPerson.h"
#import "RevanStudent.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[RevanStudent alloc];
[RevanPerson alloc];
}
@end
打印輸出:
2018-07-03 02:31:31.316817+0800 04-initialize[14221:880196] RevanPerson + initialize
2018-07-03 02:31:31.316995+0800 04-initialize[14221:880196] RevanStudent + initialize
- 源碼分析
- a)當(dāng)當(dāng)前類需要初始化的時候調(diào)用_class_initialize函數(shù)來初始化
- b)判斷當(dāng)前類是否有父類废士,父類是否需要初始化化,如果父類存在并且需要初始化時蝇完,又會調(diào)用_class_initialize函數(shù)來初始化官硝。所以會先調(diào)用父類的 + initialize方法矗蕊,再調(diào)用子類的 + initialize方法
void _class_initialize(Class cls)
{
assert(!cls->isMetaClass());
Class supercls;
bool reallyInitialize = NO;
// Make sure super is done initializing BEFORE beginning to initialize cls.
// See note about deadlock above.
//獲得父類
supercls = cls->superclass;
//存在父類對象并且父類沒有初始化,執(zhí)行遞歸初始化方法氢架,給父類初始化
if (supercls && !supercls->isInitialized()) {
_class_initialize(supercls);
}
// Try to atomically set CLS_INITIALIZING.
{
monitor_locker_t lock(classInitLock);
//如果傳進(jìn)來的類沒有初始化傻咖,就給類初始化并且reallyInitialize設(shè)置為YES
if (!cls->isInitialized() && !cls->isInitializing()) {
cls->setInitializing();
reallyInitialize = YES;
}
}
///已經(jīng)初始化了
if (reallyInitialize) {
// We successfully set the CLS_INITIALIZING bit. Initialize the class.
// Record that we're initializing this class so we can message it.
_setThisThreadIsInitializingClass(cls);
if (MultithreadedForkChild) {
// LOL JK we don't really call +initialize methods after fork().
performForkChildInitialize(cls, supercls);
return;
}
// Send the +initialize message.
// Note that +initialize is sent to the superclass (again) if
// this class doesn't implement +initialize. 2157218
if (PrintInitializing) {
_objc_inform("INITIALIZE: thread %p: calling +[%s initialize]",
pthread_self(), cls->nameForLogging());
}
// Exceptions: A +initialize call that throws an exception
// is deemed to be a complete and successful +initialize.
//
// Only __OBJC2__ adds these handlers. !__OBJC2__ has a
// bootstrapping problem of this versus CF's call to
// objc_exception_set_functions().
#if __OBJC2__
@try
#endif
{
//調(diào)用類的初始化方法,是在給類cls發(fā)送一個SEL_initialize消息
callInitialize(cls);
if (PrintInitializing) {
_objc_inform("INITIALIZE: thread %p: finished +[%s initialize]",
pthread_self(), cls->nameForLogging());
}
}
#if __OBJC2__
@catch (...) {
if (PrintInitializing) {
_objc_inform("INITIALIZE: thread %p: +[%s initialize] "
"threw an exception",
pthread_self(), cls->nameForLogging());
}
@throw;
}
@finally
#endif
{
// Done initializing.
lockAndFinishInitializing(cls, supercls);
}
return;
}
else if (cls->isInitializing()) {
// We couldn't set INITIALIZING because INITIALIZING was already set.
// If this thread set it earlier, continue normally.
// If some other thread set it, block until initialize is done.
// It's ok if INITIALIZING changes to INITIALIZED while we're here,
// because we safely check for INITIALIZED inside the lock
// before blocking.
if (_thisThreadIsInitializingClass(cls)) {
return;
} else if (!MultithreadedForkChild) {
waitForInitializeToComplete(cls);
return;
} else {
// We're on the child side of fork(), facing a class that
// was initializing by some other thread when fork() was called.
_setThisThreadIsInitializingClass(cls);
performForkChildInitialize(cls, supercls);
}
}
else if (cls->isInitialized()) {
// Set CLS_INITIALIZING failed because someone else already
// initialized the class. Continue normally.
// NOTE this check must come AFTER the ISINITIALIZING case.
// Otherwise: Another thread is initializing this class. ISINITIALIZED
// is false. Skip this clause. Then the other thread finishes
// initialization and sets INITIALIZING=no and INITIALIZED=yes.
// Skip the ISINITIALIZING clause. Die horribly.
return;
}
else {
// We shouldn't be here.
_objc_fatal("thread-safe class init in objc runtime is buggy!");
}
}
3岖研、當(dāng)子類不實現(xiàn) + initialize方法父類實現(xiàn)了 + initialize方法
- 父類RevanPerson
#import <Foundation/Foundation.h>
@interface RevanPerson : NSObject
@end
#import "RevanPerson.h"
@implementation RevanPerson
+ (void)initialize {
NSLog(@"RevanPerson + initialize");
}
@end
- 子類RevanStudent
#import "RevanPerson.h"
@interface RevanStudent : RevanPerson
@end
#import "RevanStudent.h"
@implementation RevanStudent
@end
- 測試代碼
#import "ViewController.h"
#import "RevanPerson.h"
#import "RevanStudent.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[RevanStudent alloc];
[RevanPerson alloc];
}
@end
代碼輸出:
2018-07-03 02:43:32.157267+0800 04-initialize[14409:889050] RevanPerson + initialize
2018-07-03 02:43:32.157466+0800 04-initialize[14409:889050] RevanPerson + initialize
- 會發(fā)現(xiàn)調(diào)用了2次父類中的+ initialize方法
- 原理分析
- 當(dāng)[RevanStudent alloc]的時候卿操,通過上面的源碼分析可知
- RevanStudent是否需要初始化,如果需要初始化
- 查看RevanStudent是否有父類孙援,并且查看父類是否需要初始化害淤,如果需要先給父類初始化,由于+ initialize方法的底層實現(xiàn)時給類發(fā)送了一個initialize消息拓售,所以第一次打印是RevanStudent父類的初始化
- RevanStudent父類初始化完成后窥摄,才會會RevanStudent類初始化,所以會給RevanStudent類發(fā)送一個initialize消息础淤,這時會通過isa指針找到RevanStudent的meta-class對象溪王,從類方法列表中查找,發(fā)現(xiàn)沒有值骇,在通過meta-class對象中的superclass找的父類RevanPerson的meta-class對象并且從類方法列表中查找initialize方法莹菱,如果有就實行調(diào)用。所以第二次打印的RevanPerson + initialize是RevanStudent觸發(fā)的
- RevanStudent是否需要初始化,如果需要初始化
- 當(dāng)[RevanStudent alloc]的時候卿操,通過上面的源碼分析可知
六吱瘩、load道伟、initialize方法小結(jié)
-
1.調(diào)用方式
- load是根據(jù)函數(shù)地址直接調(diào)用
- initialize是通過objc_msgSend調(diào)用
-
2.調(diào)用時刻
- load是runtime加載類、分類的時候調(diào)用(只會調(diào)用1次)
- initialize是類第一次接收到消息的時候調(diào)用使碾,每一個類只會initialize一次
- 父類的initialize方法可能會被調(diào)用多次蜜徽,但只initialize一次
-
3.load、initialize的調(diào)用順序票摇?
-
1.load
- 先調(diào)用類的load
- 先編譯的類拘鞋,優(yōu)先調(diào)用load
- 調(diào)用子類的load之前,會先調(diào)用父類的load
-
1.2.再調(diào)用分類的load
- 先編譯的分類矢门,優(yōu)先調(diào)用load
-
2.initialize
- 先初始化父類
- 再初始化子類(可能最終調(diào)用的是父類的initialize方法)
-