为什么在加载过程中我可以使用+ load方法获取所有方法?

时间:2018-10-08 11:50:37

标签: ios runtime

在应用程序进入main()函数之前,运行时系统将加载所有类和类别。显示为以下代码和控制台输出,Primary class-> BB类别-> TT类别依次加载。

我的问题是,虽然尚未加载BB类和TT类,为什么在主类的+load方法中可以提取所有方法?

源代码:

static void func() {
    uint count;
    Method *list = class_copyMethodList([ViewController class], &count);
    NSLog(@"count: %d", count);
    for (NSInteger i = 0; i < count; i++) {
        Method method = list[i];
        SEL name = method_getName(method);
        IMP imp = method_getImplementation(method);
    }
    free(list);
}
@implementation ViewController
+ (void)load {
    NSLog(@"primary class load");
    func();
}
- (void)stub {}
@end
@implementation ViewController (BB)
+ (void)load {
    NSLog(@"category (BB) load");
    func();
}
- (void)stub {}
@end
@implementation ViewController (TT)
+ (void)load {
    NSLog(@"category (TT) load");
    func();
}
- (void)stub {}
@end

控制台输出:

2018-10-08 19:40:46.726720+0800 MethodListTest[25175:1698612] primary class load
2018-10-08 19:40:46.727391+0800 MethodListTest[25175:1698612] count: 3
2018-10-08 19:40:46.727491+0800 MethodListTest[25175:1698612] category (BB) load
2018-10-08 19:40:46.727555+0800 MethodListTest[25175:1698612] count: 3
2018-10-08 19:40:46.727624+0800 MethodListTest[25175:1698612] category (TT) load
2018-10-08 19:40:46.727708+0800 MethodListTest[25175:1698612] count: 3

0 个答案:

没有答案