类的本质
1>当程序启动时,就会加载一次项目中所有的类,类加载完之后就会调用这个+load方法(分类,本身类程序启动时都会调用)
2>必须使用我们的类,当类第一次使用时调用+initialize方法(分类,本身类,有分类就只会调用分类)
3>先加载父类的,在加载子类(先调用父类的+load,在调用子类的+load)
4>先调用父类的初始化方法,在调用子类的初始化方法(+initialize)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // 2 // main.m 3 // 类的本质 4 // 5 // 6 7 8 #import <Foundation/Foundation.h> 9 #import "Person.h" 10 #import "Student.h" 11 #import "Person+EE.h" 12 int main(int argc, const char * argv[]) { 13 [[Person alloc]init]; 14 // [[Student alloc]init]; 15 16 17 return 0; 18 } 19 20 void t(){ 21 22 Person *p = [[Person alloc]init]; 23 Person *p2 = [[Person alloc]init]; 24 Person *p3 = [[Person alloc]init]; 25 26 /* 27 1>类的本质就是类本身也是一个对象,是个Class类型对象,简称类对象 28 利用Class创建person类对象 29 利用person类对象创建person类型的对象 30 */ 31 // 获取内存中的类对象 32 Class c = [p class]; 33 Class c2 = [p2 class]; 34 // 获取内存中的类对象 35 Class c3 = [Person class]; 36 NSLog(@"c=%@,c2=%p,c3=%p",c,c2,c3); 37 38 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // 2 // Person.m 3 // 类的本质 4 // 5 6 7 8 #import "Person.h" 9 10 @implementation Person 11 12 // 13 + (void)load{ 14 15 NSLog(@"调用Person--load方法"); 16 17 } 18 19 // 面试题:监听什么时候调用这个类 20 + (void)initialize{ 21 22 23 NSLog(@"调用了person--initialize方法"); 24 25 } 26 @end
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // 2 // Student.m 3 // 类的本质 4 // 5 6 7 #import "Student.h" 8 9 @implementation Student 10 11 + (void)load{ 12 13 NSLog(@"调用Student--load方法"); 14 15 } 16 + (void)initialize{ 17 18 19 NSLog(@"调用了student--initialize方法"); 20 21 } 22 @end
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // 2 // Person+EE.m 3 // 类的本质 4 // 5 6 7 #import "Person+EE.h" 8 9 @implementation Person (EE) 10 11 + (void)load{ 12 13 NSLog(@"调用Person--EE--load方法"); 14 15 } 16 17 + (void)initialize{ 18 19 20 NSLog(@"调用了person--EE--initialize方法"); 21 22 } 23 24 @end
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 Person *p = [[Person alloc]init]; 2 Person *p2 = [[Person alloc]init]; 3 Person *p3 = [[Person alloc]init]; 4 5 /* 6 1>类的本质就是类本身也是一个对象,是个Class类型对象,简称类对象 7 利用Class创建person类对象 8 利用person类对象创建person类型的对象 9 */ 10 // 获取内存中的类对象 11 Class c = [p class]; 12 Class c2 = [p2 class]; 13 // 获取内存中的类对象 14 Class c3 = [Person class]; 15 NSLog(@"c=%@,c2=%p,c3=%p",c,c2,c3);