OC中的load方法

2020-07-15  本文已影响0人  it小小菜鸟

Category的load方法什么时候调用?load方法能继承吗

  1. 在runtime加载类和分类的时候调用。类的load方法会先调用,然后才会按照编译时的顺序调用分类的load方法。
  2. 每个类、分类的+load方法,在程序运行过程中只调用一次
  3. 能继承,继承就是OC的消息发送机制,通过isa指针,再通过superclasss指针查找父类的方法。但一般不会主动调用+load方法,都是系统加载类的时候自动调用的

类和分类的+load方法的调用顺序

  1. 先调用类的+load方法,再调用分类的+load方法
  2. 类的+load方法会按照编译顺序调用,在调用+load方法的过程中,如果该类有父类,就会先调用该类父类的+load方法
  3. 分类的+load方法按照编译顺序进行调用
    注:通过下面的源码分析,根据prepare_load_methodsschedule_class_load可以得到上面的调用顺序

Category load 方法源码分析:

objc4-781版源码

注意:+load方法是根据方法地址直接调用,并不是进过objc_msgSend函数调用

源码解读过程:objc-os.mm 文件开始

  1. _objc_init 方法
  2. load_images : 加载镜像(模块),其中会调用 call_load_methods();
    3.call_load_methods(): 会先调用 call_class_loads()方法,再调用call_category_loads()方法。所以会先调用类的+load方法
  3. prepare_load_methods :准备所有的load方法,会根据_getObjc2NonlazyClassList这个数组,去循环调用schedule_class_load方法。所以_getObjc2NonlazyClassList顺序,就决定了类load方法的调用顺序。而_getObjc2NonlazyClassList顺序就直接跟编译顺序相关。
  • schedule_class_load:安排配置load方法,该函数会递归调用 schedule_class_load(cls->superclass);并把父类对象传进入。所以父类对象会先添加到数组中。所以父类的load会先调用,再调用子类的load方法
  • add_class_to_loadable_list:将class添加到数组中,
  • add_category_to_loadable_list:将category添加到数组中
  1. call_load_methods:调用load方法
  • call_class_loads:调用所有类的load方法
  • call_category_loads:调用所有分类的load方法
  • (*load_method)(cls,SEL_load):通过地址直接调用方法

先关源码:

// 该结构专门用来加载类,method 存放的方法就是类的load方法
struct loadable_class {
    Class cls;  // may be nil
    IMP method;
};
// 该结构专门用来加载分类,method 存放的方法就是分类类的load方法
struct loadable_category {
    Category cat;  // may be nil
    IMP method;
};
load_images
void
load_images(const char *path __unused, const struct mach_header *mh)
{
    if (!didInitialAttachCategories && didCallDyldNotifyRegister) {
        didInitialAttachCategories = true;
        loadAllCategories();
    }

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

void prepare_load_methods(const headerType *mhdr)
{
    size_t count, i;

    runtimeLock.assertLocked();

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

    category_t * const *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, nil);
        ASSERT(cls->ISA()->isRealized());
        add_category_to_loadable_list(cat);
    }
}
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
    schedule_class_load(cls->superclass);

    add_class_to_loadable_list(cls);
    cls->setInfo(RW_LOADED); 
}
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 {
        // 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;
}
call_class_loads
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方法的地址
        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方法
        (*load_method)(cls, @selector(load));
    }
    
    // Destroy the detached list.
    if (classes) free(classes);
}
call_category_loads
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方法地址
        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, @selector(load));
            cats[i].cat = nil;
        }
    }
....
上一篇下一篇

猜你喜欢

热点阅读