上接第一章:http://blog.csdn.net/j_akill/article/details/48556289
第二章 模型的自动归档实现
本节与上一节十分类似。
iOS开发中,可以对实现归档协议的对象,进行归档和保存在文件中。
所谓的归档就是,讲对象序列化为NSData 然后保存在本地文件。
对于上一节的student 类来说,它的归档方法按照传统的写法如下。
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:_name forKey:@"name"];
[aCoder encodeObject:_age forKey:@"age"];
[aCoder encodeObject:_grade forKey:@"grade"];
[aCoder encodeObject:_className forKey:@"className"];
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
_name = [aDecoder decodeObjectForKey:@"name"];
_age = [aDecoder decodeObjectForKey:@"age"];
_grade = [aDecoder decodeObjectForKey:@"grade"];
_className = [aDecoder decodeObjectForKey:@"className"];
return self;
}
上面这么写是没问题的。
但是其实有更简便的方法,并不用对每一个model都采用这种方法写其归档方法。
它采用的原理其实很简单,就是采用runtime获取到property list,然后遍历
propert 进行decoder 和encoder 操作。
自动归档的代码如下:
-(void)encodeWithCoder:(NSCoder *)aCoder
{
Class currentClass = self.class;
if (currentClass == NSObject.class) {
return;
}
while (currentClass && currentClass != [NSObject class])
{
unsigned int count = 0;
objc_property_t *pList = class_copyPropertyList(currentClass, &count);
if (count>0) {
for (int i=0;i<count;i++) {
NSString *key = [NSString stringWithUTF8String:property_getName(pList[i])];
[aCoder encodeObject: [self valueForKey:key] forKey:key];
}
}
currentClass = class_getSuperclass(currentClass);
free(pList);
}
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
Class currentClass = self.class;
if (currentClass == NSObject.class) {
return nil;
}
while (currentClass && currentClass != [NSObject class])
{
unsigned int count = 0;
objc_property_t *pList = class_copyPropertyList(currentClass, &count);
if (count > 0) {
for (int i = 0;i < count;i++) {
NSString *key = [NSString stringWithUTF8String:property_getName(pList[i])];
[self setValue:[aDecoder decodeObjectForKey:key] forKey:key];
}
}
currentClass = class_getSuperclass(currentClass);
free(pList);
}
return self;
}
现在仍然以这个student 类为例子。先定义好这个类,然后添加上述NSObject的扩展方法
然后初始化一个student 对象,尝试着将其进行归档化,然后对得到的数据进行接档,代码如下:
NSDictionary *dic =@{@"name":@"jakill",
@"age":@"16",
@"className":@"5年级二班",
@"grade":@"5年级"
};
//调用第一章的方法,将json转化成模型
Student *student = [Student objectFromDic:dic];
NSLog(@"%@",student.name);
NSLog(@"%@",student.age);
NSLog(@"%@",student.className);
NSLog(@"%@",student.grade);
NSData *modelData = [NSKeyedArchiver archivedDataWithRootObject:student];
Student *newStudent = [NSKeyedUnarchiver unarchiveObjectWithData:modelData];
NSLog(@"%@",newStudent.name);
NSLog(@"%@",newStudent.age);
NSLog(@"%@",newStudent.className);
NSLog(@"%@",newStudent.grade);
最终结果如下:
demo 地址:http://download.csdn.net/detail/j_akill/9118983