load方法

1、+load方法会在Runtime加载类、分类时调用

2、+load方法是根据方法地址直接调用,并不是经过objc_msgSend函数(消息发送机制)调用

每个类、分类的+load方法,在程序运行过程中只调用一次

调用顺序

1、先调用类的+load方法

1.1、按照编译先后顺序调用(先编译,先调用)
1.2、调用子类的+load方法之前会先调用父类的+load方法

2、再调用分类的+load方法

2.1、按照编译先后顺序调用(先编译,先调用)
============================== 源码解读顺序 ==============================
/*
	objc-os.mm(运行时的入口)
	1、_objc_init(运行时的初始化)
	2、load_images
	3、prepare_load_methods
    	3.1、schedule_class_load
        	3.1.1、add_class_to_loadable_list
    	3.2、add_category_to_loadable_list
	4、call_load_methods
    	4.1、call_class_loads
    	4.2、call_category_loads
    5、(*load_method)(cls, SEL_load)
*/
============================== 核心代码查看 ==============================
//	用来存放类的load方法
struct loadable_class {
    Class cls;  // may be nil
    IMP method;
};
//	用来存放分类的load方法
struct loadable_category {
    Category cat;  // may be nil
    IMP method;
};

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
    {
        mutex_locker_t lock2(runtimeLock);
        prepare_load_methods((const headerType *)mh);
    }

    // Call +load methods (without runtimeLock - re-entrant)
    call_load_methods();
}

/*
	(应该与编译的顺序有关)
	类的数组:classref_t *classlist = _getObjc2NonlazyClassList(mhdr, &count);
    分类的数组:category_t **categorylist = _getObjc2NonlazyCategoryList(mhdr, &count);
    
	对类的准备工作(里面将类加到loadable_classes数组中)
	schedule_class_load(remapClass(classlist[i]));
	将分类加loadable_categories数组的后面(数组的下标是使用++方式)
	add_category_to_loadable_list(cat);
*/
void prepare_load_methods(const headerType *mhdr)
{
    size_t count, i;

    runtimeLock.assertLocked();

    classref_t *classlist = 
        _getObjc2NonlazyClassList(mhdr, &count);
    for (i = 0; i < count; i++) {
        schedule_class_load(remapClass(classlist[i]));
    }

    category_t **categorylist = _getObjc2NonlazyCategoryList(mhdr, &count);
    for (i = 0; i < count; i++) {
        category_t *cat = categorylist[i];
        Class cls = remapClass(cat->cls);
        if (!cls) continue;  // category for ignored weak-linked class
        if (cls->isSwiftStable()) {
            _objc_fatal("Swift class extensions and categories on Swift "
                        "classes are not allowed to have +load methods");
        }
        realizeClassWithoutSwift(cls);
        assert(cls->ISA()->isRealized());
        add_category_to_loadable_list(cat);
    }
}

/*
	递归调用,获取父类cls->superclass) 确保父类是最先加到数组中去的
	schedule_class_load(cls->superclass);
	将cls加到loadable_classes数组的后面(数组的下标是使用++方式)
	add_class_to_loadable_list(cls);
	以上说明 要把cls这个类加到数组 必然先把自己的父类加到数组中(递归方式)
*/
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
    schedule_class_load(cls->superclass);

    add_class_to_loadable_list(cls);
    cls->setInfo(RW_LOADED); 
}

/*
	1、先调用类的load方法		call_class_loads();
	2、在调用分类的load方法	call_category_loads();
	接下来我们分别看看2个方法内部做了什么
*/	
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 {
        // 1. Repeatedly call class +loads until there aren't any more
        while (loadable_classes_used > 0) {
            call_class_loads();
        }

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

/*
	classes放着所有的类
	struct loadable_class *classes = loadable_classes;
	调用的顺序就需要看loadable_class数组的顺序 for (i = 0; i < used; i++) 
	(上面已经分析过loadable_class的数组顺序 在这个prepare_load_methods方法中)
	
	取出类里面的load方法,返回load方法的地址	typedef void(*load_method_t)(id, SEL);
	load_method_t load_method = (load_method_t)classes[i].method;
	
	直接用函数地址调用load方法,不使用消息机制调用objc_msgSend()
	(*load_method)(cls, SEL_load);
*/
static void call_class_loads(void)
{
    int i;
    // 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;
    
    // Call all +loads for the detached list.
    for (i = 0; i < used; i++) {
        Class cls = classes[i].cls;
        load_method_t load_method = (load_method_t)classes[i].method;
        if (!cls) continue; 

        if (PrintLoading) {
            _objc_inform("LOAD: +[%s load]\n", cls->nameForLogging());
        }
        (*load_method)(cls, SEL_load);
    }
    // Destroy the detached list.
    if (classes) free(classes);
}

/*
	取出某一个分类的方法:
	Category cat = cats[i].cat;
    load_method_t load_method = (load_method_t)cats[i].method;
    拿到内存地址直接调用:
    (*load_method)(cls, SEL_load);
*/
static bool call_category_loads(void)
{
    int i, shift;
    bool new_categories_added = NO;
    
    // 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++) {
        Category cat = cats[i].cat;
        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_method)(cls, SEL_load);
            cats[i].cat = nil;
        }
    }

    /*
		这部分代码省略
	*/
    return new_categories_added;
}

PS 此文为学习 李明杰 老师的 iOS底层原理课程所写笔记

你可能感兴趣的:(iOS底层原理,ios,objective-c,xcode)