标签:
runtime一套比较基层的c语言的API(库)
归档(OC对象-->字典—>2进制—>写入沙盒 || 目的.数据持久化)
#import <UIKit/UIKit.h>
//遵循协议
@interface NSObject (Coding)<NSCoding>
@end
#import "NSObject+Coding.h"
#import <objc/runtime.h>
@implementation NSObject (Coding)
//归档必须实现的方法
- (void)encodeWithCoder:(NSCoder *)coder
{
//属性个数
unsigned int count = 0;
//拷贝所有成员的属性,传count的地址,count的值会改变,传值和传地址的区别
Ivar * ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
// 从列表中取出属性,在c语言中指针就相当于数组
Ivar ivar = ivars[i];
//取出名称
const char * name = ivar_getName(ivar);
//转NSString,取出key
NSString *key = [NSString stringWithUTF8String:name];
//kvc取值value,归档
[coder encodeObject:[self valueForKey:key] forKey:key];
}
//在C语言中,只要用到copy就会有指针泄露,所以要释放指针
free(ivars);
}
//解挡
- (instancetype)initWithCoder:(NSCoder *)coder
{
if (self = [self init]) {
//解档
unsigned int count = 0;
//copy所有属性
Ivar * ivars = class_copyIvarList([self class], &count);
for (int i = 0; i < count; i++) {
//取属性
Ivar ivar = ivars[i];
//取name
const char * name = ivar_getName(ivar);
//转NSString
NSString *key = [NSString stringWithUTF8String:name];
//解挡
id value = [coder decodeObjectForKey:key];
//设置到自己的属性上去
[self setValue:value forKey:key];
}
//释放指针
free(ivars);
}
return self;
}
@end
用的时候直接建这样一对category文件,用的时候直接把头文件导进去就可以了
用runtime封装归档(encoding)
标签:
原文地址:http://www.cnblogs.com/Cassiedou/p/5640247.html