在前面, 我们知道了类的本质其实也是一个对象, 是Class类型, 那么类的加载过程是如何的呢?? 其实类的加载过程非常简单, 先加载父类然后再加载子类, 而且每一个类就只会加载一次, 下面让我们来看看~
例子:
#import <Foundation/Foundation.h>
@interface Person : NSObject
+ (void)load;
@end
@implementation Person
+ (void)load
{
NSLog(@"Person-----load");
}
@end
@interface Student : Person
+ (void)load;
@end
@implementation Student
+ (void)load
{
NSLog(@"Student-----load");
}
@end
int main()
{
return 0;
}
在main()函数里, 并没有调用所设定的类方法, load这个类方法是系统自动调用的, 所以不需要我们自行去调用.
结果:
2015-01-24 14:14:45.451 07-类的本质[10689:1160313] Person----load
2015-01-24 14:14:45.452 07-类的本质[10689:1160313] Student----load
从结果, 我们就看的出来, 系统先加载Person, 然后再加载Student.
那如果我们需要监听它是什么时候加载呢? 还有一个方法叫做+ (void)initialize, 下面让我们来看看:
#import <Foundation/Foundation.h>
@interface Person : NSObject
+ (void)load;
@end
@implementation Person
+ (void)load
{
NSLog(@"Person-----load");
}
+ (void)initialize
{
NSLog(@"Person-initialize");
}
@end
@interface Student : Person
+ (void)load;
@end
@implementation Student
+ (void)load
{
NSLog(@"Student-----load");
}
+ (void)initialize
{
NSLog(@"Student-initialize");
}
@end
int main()
{
[[Student alloc]init];
return 0;
}
结果:
2015-01-24 14:24:18.588 07-类的本质[10729:1164951] Person----load
2015-01-24 14:24:18.589 07-类的本质[10729:1164951] Student----load
2015-01-24 14:24:18.589 07-类的本质[10729:1164951] Person-initialize
2015-01-24 14:24:18.590 07-类的本质[10729:1164951] Student-initialize
如果我们把main()函数里的改一下:
int main()
{
[[Person alloc]init];
return 0;
}
那么结果就是:
2015-01-24 14:25:17.760 07-类的本质[10738:1165590] Person----load
2015-01-24 14:25:17.761 07-类的本质[10738:1165590] Student----load
2015-01-24 14:25:17.761 07-类的本质[10738:1165590] Person-initialize
原因其实很简单, 在main()函数中, 如果我们有加载到子类的话, 那么initialize方法就是从父类一直加载到子类, 但如果只用到父类的话, 那么子类就不会被加载.
load方法详解: 当程序启动的时候, 就会加载一次项目中所有的类, 类加载完毕后就会调用+ (void)load方法.
好了, 这次我们就讲到这里, 下次我们继续~~~