Category

一、基本使用

  • 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的底层结构类型

xcrun  -sdk  iphoneos  clang  -arch  arm64  -rewrite-objc 
RevanPerson+RevanRun.m -o RevanPerson+RevanRun.cpp
  • Category结构类型,是struct _category_t 结构体类型
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;//协议列表
    const struct _prop_list_t *properties;//属性列表
};
  • 为了看到更加详细的各个参数的情况,给分类再添加一些属性、代理、协议
#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是一个结构体:类型如下
static struct /*_method_list_t*/ {
    unsigned int entsize;  // sizeof(struct _objc_method)
    unsigned int method_count;
    struct _objc_method method_list[1];
}

在对象方法列表(一个数组):发现有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、协议列表
_OBJC_CATEGORY_PROTOCOLS_$_RevanPerson_$_RevanRun是一个结构体类型,结构如下:
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赋值中可以看到遵守的2个协议
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是一个结构体类型,结构体如下:
static struct /*_prop_list_t*/ {
    unsigned int entsize;  // sizeof(struct _prop_t)
    unsigned int count_of_properties;
    struct _prop_t prop_list[2];
}

当前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底层实现原理

  • 场景:
    • 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对象为什么可以调用Category中的sleep方法?
  • 当Category中有test对象方法和RevanPerson.h文件中申明的test对象方法一样的时候,问什么会调用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函数
/**
 @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存储协议列表
    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方法的个数
    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数组中
        if (mlist) {
            mlists[mcount++] = mlist;
            fromBundle |= entry.hi->isBundle();
        }

        property_list_t *proplist = 
            entry.cat->propertiesForMeta(isMeta, entry.hi);
        //把Category属性倒序的添加proplists数组中
        if (proplist) {
            proplists[propcount++] = proplist;
        }

        protocol_list_t *protolist = entry.cat->protocols;
        //把Category协议倒序的添加protolists数组中
        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);
}
  • 当在没有运行代码时
    Category原理一.png
  • 当运行代码时
    RevanPerson原理二.png
  • 最后方法列表
    RevanPerson原理三.png
  • 小结:
    • 在分类和类中有相同的对象方法时,因为在class对象的对象方法列表中Category中的方法排在前面
    • 当有多个Category时并且有相同方法,具体调用哪一个Category中的方法,遵守先被编译的Category方法排在方法列表中的后面,但是一定在class对象中相同方法的前面

四、+load方法

+load方法会在runtime加载类、分类时调用,并且每个类、分类的+load在程序运行过程中只调用一次

1、一个类的+load方法和分类的+load方法调用的先后顺序

  • 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:调用 +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;
}
  • 调用类的+load方法call_class_loads,直接获得程序中的所有类,并且直接执行+load方法
static void call_class_loads(void)
{
    int i;
    /*
         struct loadable_class {
             Class cls;  // may be nil
             IMP method;
         };
        这个结构体中的 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是在准备加载类的时候,计算出类的个数,后面具体分析
        通过for循环来调用所有类的+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函数指针
        load_method_t load_method = (load_method_t)classes[i].method;
        if (!cls) continue; 

        if (PrintLoading) {
            _objc_inform("LOAD: +[%s load]\n", cls->nameForLogging());
        }
        //直接执行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;
}
  • 调用分类的+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));
            }
            //执行类的+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;
}
  • 小结:
    • 从上面的分析可以很肯定的一点是,在类和分类同时存在的情况下,肯定是先执行类的+load方法之后才执行分类的+load方法

2、多个类的+load方法调用顺序

  • 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

  • 编译顺序
    加载类的+load的编译顺序.png
  • 输出打印

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
  • 调整编译顺序
    -
  • 输出打印:
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);
        //准备加载load方法
        prepare_load_methods((const headerType *)mh);
    }
    //Revan:调用 +load方法
    // Call +load methods (without runtimeLock - re-entrant)
    call_load_methods();
}
  • 3、刚才分析加载load方法(call_load_methods),在里面我们看到了存储类和分类的数组,那么这个数组中的值是什么时候加载的呢?从上面的源码可以发现在加载call_load_methods函数的前面有一个准备加载load方法的函数prepare_load_methods函数
void prepare_load_methods(const headerType *mhdr)
{
    size_t count, i;

    runtimeLock.assertWriting();
    //_getObjc2NonlazyClassList:获取objc不是懒加载类的列表
    //这个方法应该是获得程序中所有的类
    //typedef struct classref * classref_t;
    classref_t *classlist = 
        _getObjc2NonlazyClassList(mhdr, &count);
    //通过遍历存储类的数组,
    for (i = 0; i < count; i++) {
        /*
            把类传入到定制加载类的load函数中(schedule_class_load)
            如果传入的是一个子类,那么他会一层一层取到cls的父类
            然后在一个一个的把类添加到一个数组中(add_class_to_loadable_list函数实现)
         */
        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转化成类
        Class cls = remapClass(cat->cls);
        if (!cls) continue;  // category for ignored weak-linked class
        realizeClass(cls);
        assert(cls->ISA()->isRealized());
        //获取分类数组
        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);
    //把类一个一个的添加到数组中
    add_class_to_loadable_list(cls);
    cls->setInfo(RW_LOADED); 
}
  • 5、使用add_class_to_loadable_list函数把类加载到一个数组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;
     所以第一次会进入if判断中
        loadable_classes_allocated = 16
     
     在执行了call_class_loads函数后:
     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数组分配空间
        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;
    //下标++
    loadable_classes_used++;
}
  • 小结:
    • 可以肯定的是在有多个类的时候,加载类的+load方法的先后顺序是要看这些类的编译顺的,先编译先调用类的load方法

4、一个类和子类的+load方法调用顺序

  • 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
  • 小结:
    • 通过上面的源码分析,我们可以知道,在准备加载类的load方法中有一个schedule_class_load函数,在这个函数中会递归调用schedule_class_load函数传入父类,然后再调用add_class_to_loadable_list函数把类一个一个追加到数组loadable_classes中,由于在使用数组loadable_classes的时候是用的for循环,从前往后一个一个取值,所以会先调用父类的load方法再调用子类的load方法。
  • 源码辅助理解
//定制化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);
    //把类一个一个的添加到数组中
    add_class_to_loadable_list(cls);
    cls->setInfo(RW_LOADED); 
}

//把类加入到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;
     所以第一次会进入if判断中
        loadable_classes_allocated = 16
     
     在执行了call_class_loads函数后:
     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数组分配空间
        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;
    //下标++
    loadable_classes_used++;
}

5、当类有Category并且子类也有Category的时候+load调用顺序

  • 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);
        //准备加载load方法
        prepare_load_methods((const headerType *)mh);
    }
    //Revan:调用 +load方法
    // Call +load methods (without runtimeLock - re-entrant)
    call_load_methods();
}
  • 5.1、runtime加载代码中有多少个类的
  • 5.1.1、准备加载load方法(prepare_load_methods),在里面有些注释。在获取类的load方法和获取分类的load方法大致是一样的,唯一不一样的地方是在遍历获取类的load中是调用了一个加载类的load方法的定制函数(schedule_class_load函数),这个函数中自己调用自己,传入的参数是父类,通过递归来获得父类,最后在执行add_class_to_loadable_list来把类的load方法都添加到loadable_classes数组中;添加分类的load方法是没有递归父类的load方法这一步,直接使用add_category_to_loadable_list函数添加分类的load方法到loadable_categories数组中
void prepare_load_methods(const headerType *mhdr)
{
    size_t count, i;

    runtimeLock.assertWriting();
    //_getObjc2NonlazyClassList:获取objc不是懒加载类的列表
    //这个方法应该是获得程序中所有的类
    //typedef struct classref * classref_t;
    classref_t *classlist = 
        _getObjc2NonlazyClassList(mhdr, &count);
    //通过遍历存储类的数组,
    for (i = 0; i < count; i++) {
        /*
            把类传入到定制加载类的load函数中(schedule_class_load)
            如果传入的是一个子类,那么他会一层一层取到cls的父类
            然后在一个一个的把类添加到一个数组中(add_class_to_loadable_list函数实现)
         */
        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转化成类
        Class cls = remapClass(cat->cls);
        if (!cls) continue;  // category for ignored weak-linked class
        realizeClass(cls);
        assert(cls->ISA()->isRealized());
        //获取分类数组
        add_category_to_loadable_list(cat);
    }
}
  • 类的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);
    //把类一个一个的添加到数组中
    add_class_to_loadable_list(cls);
    cls->setInfo(RW_LOADED); 
}
  • 把类的load方法添加到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;
     所以第一次会进入if判断中
        loadable_classes_allocated = 16
     
     在执行了call_class_loads函数后:
     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数组分配空间
        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;
    //下标++
    loadable_classes_used++;
}
  • 添加分类的load方法到loadable_categories数组中
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调用类或者分类的load方法
  • 5.2.1、call_load_methods函数,通过loadable_classes_used来判断是否有类,如何有就调用类的call_class_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;
}
  • 5.2.2、调用触发(类调用load方法的函数(call_class_loads))在这里存储类的数组classes,遍历数组classes,直接拿到method中的load方法直接执行。所以call_class_loads函数调用过后类的load方法都已经调用完成
static void call_class_loads(void)
{
    int i;
    /*
         struct loadable_class {
             Class cls;  // may be nil
             IMP method;
         };
        这个结构体中的 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是在准备加载类的时候,计算出类的个数,后面具体分析
        通过for循环来调用所有类的+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函数指针
        load_method_t load_method = (load_method_t)classes[i].method;
        if (!cls) continue; 

        if (PrintLoading) {
            _objc_inform("LOAD: +[%s load]\n", cls->nameForLogging());
        }
        //直接执行cls类的load方法
        (*load_method)(cls, SEL_load);
    }
    
    // Destroy the detached list.
    if (classes) free(classes);
}
  • 5.2.3、触发(分类调用load函数(call_category_loads))拿到存储分类的loadable_categories数组,通过遍历数组loadable_categories,来获得method和转换的cls,之后直接调用
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));
            }
            //执行类的+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;
}
  • 小结
    • a)调用类的+load方法
      • 先调用类的+load方法,按照编译先后顺序调用(先编译,先调用)
      • 调用子类的+load之前会先调用父类的+load方法
    • b)调用分类的+load方法
      • 按照编译先后顺序调用(先编译,先调用)

五、+initialize方法

+initialize方法会在类第一次接收到消息时调用

  • 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方法没有调用,所以当代码中不使用RevanPerson这个类的时候,是不会触发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如何调用

  • 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
  • 发现是使用的分类中的+initialize方法。调整2个分类的编译顺序后,发现打印结果发生改变
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函数
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函数判断cls类是否已经初始化
     当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、通过传入的参数initialize和调用类的isInitialized函数的返回结果一起来判断是否调用_class_initialize函数,是否要初始化类;当这个类需要初始化(initialize=YES)并且还没有初始化(isInitialized函数返回值为NO时)会调用_class_initialize函数进行初始化。
    • 4.4.1、首先会找到cls的父类,查看父类是否存在,父类是否已经初始化,当父类也需要初始化的时候会递归调用_class_initialize函数
    • 4.4.2、在父类初始化完成以后,如果当前类没有初始化,那么进行当前类的初始化并且把reallyInitialize=YES
    • 4.4.3、当前类已经初始化完成后调用callInitialize函数
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;
    //存在父类对象并且父类没有初始化,执行递归初始化方法,给父类初始化
    if (supercls  &&  !supercls->isInitialized()) {
        _class_initialize(supercls);
    }
    
    // Try to atomically set CLS_INITIALIZING.
    {
        monitor_locker_t lock(classInitLock);
        //如果传进来的类没有初始化,就给类初始化并且reallyInitialize设置为YES
        if (!cls->isInitialized() && !cls->isInitializing()) {
            cls->setInitializing();
            reallyInitialize = YES;
        }
    }
    
    ///已经初始化了
    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
        {
            //调用类的初始化方法,是在给类cls发送一个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、调用初始化callInitialize,实质是给当前类发送一个SEL_initialize消息
/**
 调用初始化方法(给类发送SEL_initialize初始化消息)

 @param cls 类
 */
void callInitialize(Class cls)
{
    ((void(*)(Class, SEL))objc_msgSend)(cls, SEL_initialize);
    asm("");
}
  • 小结
    • 调用+initialize本质是给一个类发送一个initialize消息,由于消息机制的本质(isa指针、supercla指针),所以会优先调用分类的方法

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)当当前类需要初始化的时候调用_class_initialize函数来初始化
    • b)判断当前类是否有父类,父类是否需要初始化化,如果父类存在并且需要初始化时,又会调用_class_initialize函数来初始化。所以会先调用父类的 + initialize方法,再调用子类的 + 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;
    //存在父类对象并且父类没有初始化,执行递归初始化方法,给父类初始化
    if (supercls  &&  !supercls->isInitialized()) {
        _class_initialize(supercls);
    }
    
    // Try to atomically set CLS_INITIALIZING.
    {
        monitor_locker_t lock(classInitLock);
        //如果传进来的类没有初始化,就给类初始化并且reallyInitialize设置为YES
        if (!cls->isInitialized() && !cls->isInitializing()) {
            cls->setInitializing();
            reallyInitialize = YES;
        }
    }
    
    ///已经初始化了
    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
        {
            //调用类的初始化方法,是在给类cls发送一个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、当子类不实现 + initialize方法父类实现了 + 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
  • 会发现调用了2次父类中的+ initialize方法
  • 原理分析
    • 当[RevanStudent alloc]的时候,通过上面的源码分析可知
      • RevanStudent是否需要初始化,如果需要初始化
        • 查看RevanStudent是否有父类,并且查看父类是否需要初始化,如果需要先给父类初始化,由于+ initialize方法的底层实现时给类发送了一个initialize消息,所以第一次打印是RevanStudent父类的初始化
      • RevanStudent父类初始化完成后,才会会RevanStudent类初始化,所以会给RevanStudent类发送一个initialize消息,这时会通过isa指针找到RevanStudent的meta-class对象,从类方法列表中查找,发现没有,在通过meta-class对象中的superclass找的父类RevanPerson的meta-class对象并且从类方法列表中查找initialize方法,如果有就实行调用。所以第二次打印的RevanPerson + initialize是RevanStudent触发的

六、load、initialize方法小结

  • 1.调用方式

    • load是根据函数地址直接调用
    • initialize是通过objc_msgSend调用
  • 2.调用时刻

    • load是runtime加载类、分类的时候调用(只会调用1次)
    • initialize是类第一次接收到消息的时候调用,每一个类只会initialize一次
    • 父类的initialize方法可能会被调用多次,但只initialize一次
  • 3.load、initialize的调用顺序?

    • 1.load

      • 先调用类的load
      • 先编译的类,优先调用load
      • 调用子类的load之前,会先调用父类的load
    • 1.2.再调用分类的load

      • 先编译的分类,优先调用load
    • 2.initialize

      • 先初始化父类
      • 再初始化子类(可能最终调用的是父类的initialize方法)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,033评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,725评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,473评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,846评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,848评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,691评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,053评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,700评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,856评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,676评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,787评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,430评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,034评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,990评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,218评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,174评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,526评论 2 343

推荐阅读更多精彩内容