+load、+initialize、-init调用时机

+load、+initialize、-init调用时机_第1张图片
+load、+initialize、-init调用时机

Person

#pragma mark - Person
@interface Person : NSObject

@end

@implementation Person

+ (void)load {
    printf("%s\n", __func__);
}

+ (void)initialize {
    printf("%s\n", __func__);
}

- (instancetype)init {
    self = [super init];
    if (self) {
        printf("%s\n", __func__);
    }
    return self;
}
@end

Person Category

#pragma mark - Person (Male)
@interface Person (Category)

@end

@implementation Person (Category)

+ (void)load {
    printf("%s\n", __func__);
}

@end

Father

#pragma mark - Father
@interface Father : Person

@end

@implementation Father

+ (void)load {
    printf("%s\n", __func__);
}

+ (void)initialize {
    printf("%s\n", __func__);
}

- (instancetype)init {
    self = [super init];
    if (self) {
        printf("%s\n", __func__);
    }
    return self;
}

@end

Step 1

int main(int argc, const char * argv[]) {
    @autoreleasepool {

    }
    return 0;
}

运行程序,我们看一下输出日志:
+[Person load]
+[Father load]
+[Person(Category) load]

Step 2

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        [Person description];
    }
    return 0;
}

运行程序,我们看一下输出日志:
+[Person load]
+[Father load]
+[Person(Category) load]
+[Person initialize]

Step 3

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        [Person new];
    }
    return 0;
}

运行程序,我们看一下输出日志:
+[Person load]
+[Father load]
+[Person(Category) load]
+[Person initialize]
-[Person init]

Step 4

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        [Father new];
    }
    return 0;
}

运行程序,我们看一下输出日志:
+[Person load]
+[Father load]
+[Person(Category) load]
+[Person initialize]
+[Father initialize]
-[Person init]
-[Father init]

>根据上面的现象可知:
+load:程序运行时自动调用
+initialize:第一次用到这个类时调用,只会调用一次
-init:对象的初始化方法,创建对象时调用

程序启动,目中所有类的+load方法调用,创建对象父类先调用+initialize,然后是子类的+initialize,然后是父类的-init,最后是自己的-init

你可能感兴趣的:(+load、+initialize、-init调用时机)