iOS

Load() +initialize()

2017-03-11  本文已影响13人  小万叔叔

Prepare

//Father 
@implementation Father 
+ (void)load {
    NSLog(@"=== father load");
}

+ (void)initialize {
    NSLog(@"=== father initialize");
}
@end

//Son
@interface Son : Father
@end
@implementation Son 
+ (void)load {
    NSLog(@"=== Son load");
}

+ (void)initialize {
    NSLog(@"=== Son initialize");
}
@end
//Father Category
@implementation Father (category)
+ (void)load {
    NSLog(@"=== father category load");
}

+ (void)initialize {
    NSLog(@"=== father category initialize");
}
@end
//Son category
@implementation Son (category)
+ (void)load {
    NSLog(@"=== Son category load");
}

+ (void)initialize {
    NSLog(@"=== Son category initialize");
}
@end

//Compile Source Order
Son.m
Father.m
Son+category.m
Father+category.m

//OutPut
 === father load
 === Son load
 === Son category load
 === father category load
//Father
@implementation Father 
+ (void)initialize {
    NSLog(@"=== father initialize");
}
@end
//Son
@interface Son : Father
@end
@implementation Son 
//+ (void)initialize {
//    NSLog(@"=== Son initialize");
//}
@end
//AppDelegate.m
[Son new]
[Father new]

//OutPut
=== father initialize
=== father initialize

//Resolver
+ (void)initialize {
    if (self == [Father class]){
        NSLog(@"=== father initialize");
    }
}

B: 如果 Category 也重写了Initialize, 会override, 也就是原来类里面的Initialize 不会被调用。

//最上面源码里面的输出
=== father category initialize
=== Son category initialize

适用场景

上一篇 下一篇

猜你喜欢

热点阅读