Category

2018-07-03  本文已影响14人  紫荆秋雪_文

一、基本使用

#import <Foundation/Foundation.h>

@interface RevanPerson : NSObject
- (void)test;
@end
#import "RevanPerson.h"

@implementation RevanPerson
- (void)test {
    NSLog(@"RevanPerson -test");
}
@end

#import "RevanPerson.h"

@interface RevanPerson (RevanRun)
- (void)run;
@end

#import "RevanPerson+RevanRun.h"

@implementation RevanPerson (RevanRun)
- (void)run {
    NSLog(@"RevanPerson (RevanRun) -run");
}
@end

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

xcrun  -sdk  iphoneos  clang  -arch  arm64  -rewrite-objc 
RevanPerson+RevanRun.m -o RevanPerson+RevanRun.cpp
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
_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,
};
_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}}
};
_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
};
_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底层实现原理

#import <Foundation/Foundation.h>

@interface RevanPerson : NSObject
- (void)test;
@end
#import "RevanPerson.h"

@implementation RevanPerson
- (void)test {
    NSLog(@"RevanPerson -test");
}
@end

#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

1、找到_objc_init
2、找到map_images
3、找到map_images_nolock
4、找到_read_images
5、找到remethodizeClass
6、找到attachCategories
7、找到attachCategories
8、找到attachLists

/**
 @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);
}

四、+load方法

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

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

#import <Foundation/Foundation.h>

@interface RevanPerson : NSObject

@end
#import "RevanPerson.h"

@implementation RevanPerson
+ (void)load {
    NSLog(@"RevanPerson");
}
@end

#import "RevanPerson.h"

@interface RevanPerson (RevanRun)

@end

#import "RevanPerson+RevanRun.h"

@implementation RevanPerson (RevanRun)
+ (void)load {
     NSLog(@"RevanPerson (RevanRun) +load");
}
@end

#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的源码

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);
}

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();
}
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;
}
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);
}
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;
}
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;
}

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

#import <Foundation/Foundation.h>

@interface RevanPerson : NSObject

@end
#import "RevanPerson.h"

@implementation RevanPerson

+ (void)load {
    NSLog(@"RevanPerson +load");
}

@end
#import <Foundation/Foundation.h>

@interface RevanCat : NSObject

@end
#import "RevanCat.h"

@implementation RevanCat

+ (void)load {
    NSLog(@"RevanCat +load");
}

@end

#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
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
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);
}
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();
}
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);
    }
}
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); 
}
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++;
}

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

#import <Foundation/Foundation.h>

@interface RevanPerson : NSObject

@end

#import "RevanPerson.h"

@implementation RevanPerson
+ (void)load {
    NSLog(@"RevanPerson");
}
@end

#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
//定制化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调用顺序

#import <Foundation/Foundation.h>

@interface RevanPerson : NSObject

@end
#import "RevanPerson.h"

@implementation RevanPerson
+ (void)load {
    NSLog(@"RevanPerson");
}
@end

#import "RevanPerson.h"

@interface RevanPerson (RevanRun)

@end

#import "RevanPerson+RevanRun.h"

@implementation RevanPerson (RevanRun)
+ (void)load {
     NSLog(@"RevanPerson (RevanRun) +load");
}
@end

#import "RevanPerson.h"

@interface RevanPerson (RevanSleep)

@end
#import "RevanPerson+RevanSleep.h"

@implementation RevanPerson (RevanSleep)
+(void)load {
     NSLog(@"RevanPerson (RevanSleep) +load");
}
@end

#import "RevanPerson.h"

@interface RevanStudent : RevanPerson

@end
#import "RevanStudent.h"

@implementation RevanStudent
+ (void)load {
    NSLog(@"RevanStudent");
}
@end


#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方法的源码分析

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_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();
}
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);
    }
}
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); 
}
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++;
}
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++;
}
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;
}
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);
}
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;
}

五、+initialize方法

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

#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
#import "ViewController.h"
#import "RevanPerson.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [RevanPerson alloc];
}

@end

1、但类和分类中都有+ initialize方法时,initialize如何调用

#import <Foundation/Foundation.h>

@interface RevanPerson : NSObject

@end
#import "RevanPerson.h"

@implementation RevanPerson
+ (void)initialize {
    NSLog(@"RevanPerson + initialize");
}
@end
#import "RevanPerson.h"

@interface RevanPerson (RevanRun)

@end
#import "RevanPerson+RevanRun.h"

@implementation RevanPerson (RevanRun)

+ (void)initialize {
    NSLog(@"RevanPerson (RevanRun) + initialize");
}

@end
#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
2018-07-03 01:56:12.115167+0800 04-initialize[13899:856044] RevanPerson (RevanRun) + initialize
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);
}
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;
}
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;
}
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!");
    }
}
/**
 调用初始化方法(给类发送SEL_initialize初始化消息)

 @param cls 类
 */
void callInitialize(Class cls)
{
    ((void(*)(Class, SEL))objc_msgSend)(cls, SEL_initialize);
    asm("");
}

2、类和子类都有+initialize

#import <Foundation/Foundation.h>

@interface RevanPerson : NSObject

@end
#import "RevanPerson.h"

@implementation RevanPerson
+ (void)initialize {
    NSLog(@"RevanPerson + initialize");
}
@end
#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
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方法

#import <Foundation/Foundation.h>

@interface RevanPerson : NSObject

@end
#import "RevanPerson.h"

@implementation RevanPerson
+ (void)initialize {
    NSLog(@"RevanPerson + initialize");
}
@end
#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

六、load、initialize方法小结

上一篇 下一篇

猜你喜欢

热点阅读