举两个例子 一个animal 类 ,一个它的子类 Money
** Animal 类**
@interface Animal : NSObject
@end
@implementation Animal
- (instancetype)init
{
self = [super init];
if (self) {
NSLog(@"init:%@",[self class]);
}
return self;
}
+ (void)initialize {
[super initialize];
NSLog(@"initialize_1_Class:%@",[self class]);
}
@end
** Monkey 类**
@interface Monkey : Animal
@end
@implementation Monkey
- (instancetype)init
{
self = [super init];
if (self) {
NSLog(@"init:%@",[self class]);
}
return self;
}
+ (void)initialize {
[super initialize];
NSLog(@"initialize_2_Class:%@",[self class]);
}
@end
** 运行和 打印结果 **
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Animal * animal1 = [[Animal alloc]init];
Animal * animal2 = [[Animal alloc]init];
Animal * animal3 = [[Animal alloc]init];
Animal * animal4 = [[Animal alloc]init];
Monkey * monkey1 = [[Monkey alloc]init];
Monkey * monkey2 = [[Monkey alloc]init];
Monkey * monkey3 = [[Monkey alloc]init];
}
2016-07-12 17:34:58.918 InitiazeAndLoad[5982:208086] initialize_1_Class:Animal
2016-07-12 17:34:58.918 InitiazeAndLoad[5982:208086] init:Animal
2016-07-12 17:34:58.918 InitiazeAndLoad[5982:208086] init:Animal
2016-07-12 17:34:58.918 InitiazeAndLoad[5982:208086] init:Animal
2016-07-12 17:34:58.919 InitiazeAndLoad[5982:208086] init:Animal
2016-07-12 17:34:58.919 InitiazeAndLoad[5982:208086] initialize_1_Class:Monkey
2016-07-12 17:34:58.919 InitiazeAndLoad[5982:208086] initialize_2_Class:Monkey
2016-07-12 17:34:58.919 InitiazeAndLoad[5982:208086] init:Monkey
2016-07-12 17:34:58.919 InitiazeAndLoad[5982:208086] init:Monkey
2016-07-12 17:34:58.919 InitiazeAndLoad[5982:208086] init:Monkey
2016-07-12 17:34:58.920 InitiazeAndLoad[5982:208086] init:Monkey
2016-07-12 17:34:58.920 InitiazeAndLoad[5982:208086] init:Monkey
2016-07-12 17:34:58.920 InitiazeAndLoad[5982:208086] init:Monkey
** 总结 **
- initialize 在相同的类的时候只初始化一次,如果有继承类,还会调用一次。2.我们应该只是初始化一些 固定的值