黑马程序员_类的深入研究
类也是个对象
* 其实类也是一个对象,是Class类型的对象,简称“类对象”
* Class类型的定义
typedef struct objc class *Class;
* 类名就代表着类对象,每个类只有一个类对象
/*
* 1.当程序启动时,就会加载项目中所有的类和分类,而且加载后会调用每个类和分类的+load方法。只会调用
一次。
* 2.当第一次使用某个类时,就会调用当前类的+initialize方法。
* 3.先加载父类,再加载子类(先调用父类的+load方法,再调用子类的+load方法)
* 先初始化父类,再初始化子类(先调用父类的+initialize方法,再调用子类的+initialize方法)
*/
// +initialize方法可以监听类在什么时候被使用,就是监听类的初始化过程.
#import <Foundation/Foundation.h>
/****************** Person ******************/
@interface Person : NSObject
@property int age;
+ void(test);
@end
@implementation Person
+ void(test)
{
NSLog (@"Person --- +test");
}
// 当程序启动的时候,就会加载一次项目中所有的类,类加载完毕后就会调用+load方法;在类被加载的时候调
用; 系统自动调用
// 不管用不用,程序已启动就加载
+ (void)load
{
NSLog (@"Person --- load");
}
// 当第一次使用这个类的时候,就会调用一次+initialize方法
+ (void)initialize
{
NSLog (@"Person --- initialize");
}
@end
/****************** Student ******************/
@interface Student : Person
@end
@implementation Student
// 在类被加载的时候调用; 系统自动调用
+ (void)load
{
NSLog (@"Student --- load");
}
+ (void)initialize
{
NSLog (@"Student --- initialize");
}
@end
/****************** GoodStudent ******************/
@interface GoodStudent : Student
@end
@implementation GoodStudent
// 在类被加载的时候调用; 系统自动调用
+ (void)load
{
NSLog (@"GoodStudent --- load");
}
+ (void)initialize
{
NSLog (@"GoodStudent --- initialize");
}
@end
/****************** Person (MJ) ******************/
@interface Person (MJ)
@end
@implementation Person (MJ)
// 加载load的时候,类和分类的load都会被调用
+ (void)load
{
NSLog (@"Person (MJ) --- load");
}
// 优先使用分类的initialize方法
+ (void)initialize
{
NSLog (@"Person (MJ) --- initialize");
}
@end
/****************** main ******************/
int main()
{
[[Person alloc] init];
[[Student alloc] init];
[[GoodStudent alloc] init];
return 0;
}
void test1()
{
Person *p = [[Person alloc] init];
[Person test];
// 内存中的类对象; 类对象就是类; 类名就是类对象
Class c = [p class];
[c test];
Person *p2 = [[c alloc] init];
}
void test()
{
// 利用Person这个类创建了2个Person类型的对象
Person *p = [[Person alloc] init];
Person *p2 = [[Person alloc] init];
// 获取内存中的类对象
Class c = [p class];
Class c2 = [p2 class];
NSLog (@"c = %p, c2 = %p", c, c2);
// 获取内存中的类对象
Class c3 = [Person class];
NSLog (@"c = %p, c2 = %p, c3 = %p", c, c2, c3);
// 类本身也是一个对象,是个Class类型的对象,简称类对象。
/*
利用 Class 创建 Person类对象
利用 Person类对象 创建Person类型的对象
*/
}