runtime——归档
#import <Foundation/Foundation.h>
@interface PYPeople : NSObject
@property (nonatomic, assign) int age;
@property (nonatomic, assign) int height;
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age2;
@property (nonatomic, assign) int height2;
@property (nonatomic, assign) int age3;
@property (nonatomic, assign) int height3;
@property (nonatomic, assign) int age4;
@property (nonatomic, assign) int height4;
@end
#import "PYPeople.h"
#import <objc/runtime.h>
@implementation PYPeople
-(void)encodeWithCoder:(NSCoder *)encoder{
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([PYPeople class], &count);
for (int i=0; i<count; i++) {
Ivar ivar = ivars[i];
const char*name =ivar_getName(ivar);
NSString *key =[NSString stringWithUTF8String:name];
id value =[self valueForKey:key];
[encoder encodeObject:value forKey:key];
}
free(ivars);
}
-(id)initWithCoder:(NSCoder *)decoder
{
if (self= [super init]) {
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([PYPeople class], &count);
for (int i = 0; i<count; i++) {
// 取出i位置对应的成员变量
Ivar ivar = ivars[i];
// 查看成员变量
const char *name = ivar_getName(ivar);
// 归档
NSString *key = [NSString stringWithUTF8String:name];
id value = [decoder decodeObjectForKey:key];
// 设置到成员变量身上
[self setValue:value forKey:key];
}
free(ivars);
}
return self;
}
@end
runtime机制首先要了解下面几个问题 1相关的头文件和函数 1> 头文件
-
<objc/runtime.h>
- <objc/message.h> 利用头文件,我们可以查看到runtime中的各个方法!
2> 相关应用
- NSCoding(归档和解档, 利用runtime遍历模型对象的所有属性)
- 字典 --> 模型 (利用runtime遍历模型对象的所有属性, 根据属性名从字典中取出对应的值, 设置到模型的属性上)
- KVO(利用runtime动态产生一个类)
- 用于封装框架(想怎么改就怎么改) 这就是我们runtime机制的只要运用方向
3> 相关函数
- objc_msgSend : 给对象发送消息
- class_copyMethodList : 遍历某个类所有的方法
- class_copyIvarList : 遍历某个类所有的成员变量
- class_..... 这是我们学习runtime必须知道的函数!
4.必备常识 1> Ivar : 成员变量 2> Method : 成员方法 从上面例子中我们看到我们定义的成员变量,如果要是动态创建方法,可以使用Method,