接到新需求要把整个页面缓存下来,在没有网络的情况下还能显示上次的页面,值得庆幸的是当初写的时候就都是用的model来存储的数据,我马上就想到用归档与反归档,更值得庆幸的是我的model有个baseModel,只要在baseModel中实现以下两个方法就可以了:
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder;
可是如果在基类中你是不知道具体子类的属性的,这样就需要用到iOS中我认为最强大的runtime了。
废话不多说,直接上代码:
#pragma mark 归档
- (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;
}
稍微讲解一下代码。
objc_property_t *pList = class_copyPropertyList(currentClass, &count);
这句代码是为了拿到本类中的所有属性,其中count代表的是属性的个数。
for (int i=0;i<count;i++) {
NSString *key = [NSString stringWithUTF8String:property_getName(pList[i])];
[aCoder encodeObject: [self valueForKey:key] forKey:key];
}
这一段就是把每一个属性都encoding了。
currentClass = class_getSuperclass(currentClass);
这句是防止父类中有属性没有encoding,所以用了一个while循环。
这样你只需要在用的时候直接archived一下,转换成NSData类型的,这样就可以放到数组中,直接write到本地,用的时候直接unarchived一下就好了。
附上使用的代码:
- (void)writePointWithArray:(NSArray *)array {
NSMutableArray *localArray = [NSMutableArray arrayWithCapacity:array.count];
for (LYNewsModel *model in array) {
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model];
[localArray addObject:data];
}
[localArray writeToFile:kPointPath atomically:YES];
}
- (NSArray *)getPoints {
NSMutableArray *array = [NSMutableArray array];
NSArray *localArray = [NSArray arrayWithContentsOfFile:kPointPath];
for (NSData *data in localArray) {
LYNewsModel *model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[array addObject:model];
}
return array;
}
网友评论