runtime即运行时这是一个基于比较底层的C语言的API,oc的幕后操作者,oc代码在运行时由编译器将其转为runtime的c语言代码其中最主要的就是消息机制,oc在调用函数是会变成一条消息发送出去属于动态过程即在编译的时候并未决定真正调用的那个函数事实证明,只有在运行时才会根据函数的名称找到对应函数的调用.
简单实例:
解档归档:当属性只有几个的时候可以轻松写完,如果有几十个属性呢
- (id)initWithCoder:(NSCoder *)aDecoder {
2 if (self = [super init]) {
3 unsigned int outCount;
4 Ivar * ivars = class_copyIvarList([self class], &outCount);
5 for (int i = 0; i < outCount; i ++) {
6 Ivar ivar = ivars[i];
7 NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
8 [self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
9 }
10 }
11 return self;
12 }
13
14 - (void)encodeWithCoder:(NSCoder *)aCoder {
15 unsigned int outCount;
16 Ivar * ivars = class_copyIvarList([self class], &outCount);
17 for (int i = 0; i < outCount; i ++) {
18 Ivar ivar = ivars[i];
19 NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
20 [aCoder encodeObject:[self valueForKey:key] forKey:key];
21 }
22 }