#import <Foundation/Foundation.h>
@interface Person : NSObject
@property NSString *name;
- (void)test;
@end
#import "Person.h"
@implementation Person
- (void)test
{
NSLog(@"call test...\n");
}
+ (void)load
{
NSLog(@"Person load>>>\n");
}
+ (void)initialize
{
NSLog(@"Person initialize>>>\n");
}
@end
#import "Person.h"
@interface Person (Jax)
- (void)study;
- (void)test;
@end
#import "Person+Jax.h"
@implementation Person (Jax)
- (void)study
{
NSLog(@"study....\n");
}
- (void)test
{
@{@"xx":@2};
NSLog(@"Person (Jax)...\n");
}
+ (void)load
{
NSLog(@"Person Jax load>>>\n");
}
+ (void)initialize
{
NSLog(@"Person Jax initialize>>>\n");
}
@end
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Person+Jax.h"
#import "Person+Song.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *p = [[Person alloc]init];
[p test];
[p study];
[p play];
Class pc =[p class];
Person *p2 = [[pc alloc]init];
[p2 test];
[p2 study];
[p2 play];
NSLog(@"%p,%p,%p\n",[p2 class],[pc class],[Person class]);
}
return 0;
}
输出:
2017-01-10 09:30:24.391 Category[897:39368] Person load>>>
2017-01-10 09:30:24.392 Category[897:39368] Person Jax load>>>
2017-01-10 09:30:24.392 Category[897:39368] Person Song load>>>
2017-01-10 09:30:24.393 Category[897:39368] Person Song initialize>>>
2017-01-10 09:30:24.393 Category[897:39368] Person (Song)…
2017-01-10 09:30:24.393 Category[897:39368] study….
2017-01-10 09:30:24.393 Category[897:39368] play…
2017-01-10 09:30:24.393 Category[897:39368] Person (Song)…
2017-01-10 09:30:24.393 Category[897:39368] study….
2017-01-10 09:30:24.393 Category[897:39368] play…
2017-01-10 09:30:24.393 Category[897:39368] 0x100002578,0x100002578,0x100002578
类也是个对象
其实类也是一个对象,是Class类型的对象,简称“类对象”
Class类型的定义
typedef struct objc_class *Class;
类名就代表着类对象,每个类只有一个类对象
+load和+initialize
+load:
在程序启动的时候会加载所有的类和分类,并调用所有类和分类的+load方法
先加载父类,再加载子类;也就是先调用父类的+load,再调用子类的+load
先加载元原始类,再加载分类
不管程序运行过程有没有用到这个类,都会调用+load加载
+initialize:
在第一次使用某个类时(比如创建对象等),就会调用一次+initialize方法
一个类只会调用一次+initialize方法,先调用父类的,再调用子类的,优先最后编译的分类。
获取类对象的2种方式
Class c = [Person class]; // 类方法
或者
Person *p = [Person new];
Class c2 = [p class]; // 对象方法类对象调用类方法
Class c = [Person class];
Person *p2 = [c new];