在开发中经常需要对一些对象进行保存,当然这是一些很轻量级的,我们首先会想到使用NSUserDefaults进行保存,但是NSUserDefaults所能直接保存的对象类型也是有限的,比如NSArray,NSData,NSDictionary,NSNumber,NSString,对于我们自己建立的模型对象,NSUserDefaults直接保存的话,就有点力不从心了,这时,我们往往要对模型对象进行归档,归档虽说实现简单,但是,试想一些,如果你的模型成员比较多,手动实现很费时间,可以新建一个NSObject的分类,使用runtime遍历属性实现归档
. h 文件
#import <Foundation/Foundation.h>
@protocol DVVCodingDelegate <NSObject>
@optional
/**
如果有不想缓存的属性,通过此代理方法返回就可以了
*/
+ (NSArray *)dvv_codingIgnoreProperties;
@end
@interface NSObject (DVVCoding)
/**
* 解码(从文件解析对象)
*/
- (void)dvv_decode:(NSCoder *)decoder;
/**
* 编码(将对象写入文件)
*/
- (void)dvv_encode:(NSCoder *)encoder;
/**
* 属性归档的实现
*/
#define DVVCodingImplementation \
- (instancetype)initWithCoder:(NSCoder *)aDecoder \
{ \
self = [super init]; \
if (self) { \
[self dvv_decode:aDecoder]; \
} \
return self; \
} \
\
- (void)encodeWithCoder:(NSCoder *)coder \
{ \
[self dvv_encode:coder]; \
}
@end
. m 文件
#import "DVVCoding.h"
#import <objc/runtime.h>
typedef NS_ENUM(NSUInteger, DVVCodingType)
{
DVVCodingTypeEncode,
DVVCodingTypeDecode,
};
@implementation NSObject (DVVCoding)
- (void)dvv_encode:(NSCoder *)encoder
{
[self dvv_codingFor:encoder type:DVVCodingTypeEncode];
}
- (void)dvv_decode:(NSCoder *)decoder
{
[self dvv_codingFor:decoder type:DVVCodingTypeDecode];
}
- (void)dvv_codingFor:(NSCoder *)coder type:(DVVCodingType)type
{
NSArray *ignoreProperties = nil;
if ([[self class] respondsToSelector:@selector(dvv_codingIgnoreProperties)])
{
ignoreProperties = (NSArray *)[[self class] performSelector:@selector(dvv_codingIgnoreProperties)];
}
if (!ignoreProperties) ignoreProperties = [NSArray array];
NSMutableArray *defaultIgnoreProperties = [NSMutableArray arrayWithObjects:@"hash", @"superclass", @"description", @"debugDescription", nil];
ignoreProperties = [defaultIgnoreProperties arrayByAddingObjectsFromArray:ignoreProperties];
unsigned int count;
objc_property_t *properties = class_copyPropertyList(self.class, &count);
for (unsigned int i = 0; i < count; i++)
{
objc_property_t property = properties[i];
const char *name = property_getName(property);
NSString *propertyName = [NSString stringWithUTF8String:name];
if (ignoreProperties)
{
BOOL flage = NO;
for (NSString *ignorePropertyName in ignoreProperties)
{
if ([propertyName isEqualToString:ignorePropertyName])
{
flage = YES;
break;
}
}
if (flage)
{
continue;
}
}
NSString *propertyValue = nil;
if (DVVCodingTypeEncode == type)
{
propertyValue = [self valueForKey:propertyName];
if(propertyValue) [coder encodeObject:propertyValue forKey:propertyName];
}
else if (DVVCodingTypeDecode == type)
{
propertyValue = [coder decodeObjectForKey:propertyName];
if(propertyValue) [self setValue:propertyValue forKey:propertyName];
}
}
free(properties);
}
@end
直接在模型对象的implementation里调用宏
#import "MMRDMUserInfo.h"
@implementation MMRDMUserInfo
DVVCodingImplementation
/**
如果有不想缓存的属性,通过此代理方法返回
@return 忽略列表
*/
+ (NSArray *)dvv_codingIgnoreProperties
{
return @[ @"property_1", @"property_2" ];
}
@end