此方法基本思路是:保存对象前利用反射机制获得该对象的每个属性,再转化为字典,最后将字典写入文件。
读取对象时先将文件的内容读入字典,在利用KVC机制中的setValuesForKeysWithDictionary方法给每个属性赋值。
本方法只要为原有的类添加两个方法即可实现保存读取。
注意:本方法需要导入”运行时“头文件 objc/runtime.h,属性只能为对象类型
头文件加入两个方法声明.
-(BOOL)wirteToFile:(NSString*)fileName;
-(instancetype)initFromFile:(NSString*)fileName;
实现文件:
-(BOOL)wirteToFile:(NSString*)fileName
{
NSMutableDictionary*props = [NSMutableDictionary dictionary];
unsigned int outCount, i;
objc_property_t*properties =class_copyPropertyList([self class], &outCount);
for(i =0; i < outCount ; i++)
{
objc_property_tproperty = properties[i];
constchar* char_f =property_getName(property);
NSString*propertyName = [NSStringstringWithUTF8String:char_f];
idpropertyValue = [selfvalueForKey:(NSString*)propertyName];
if(propertyValue) [propssetObject:propertyValueforKey:propertyName];
}
free(properties);
return[propswriteToFile:fileNameatomically:YES];
}
-(instancetype)initFromFile:(NSString*)fileName
{
if(self= [superinit]) {
NSDictionary*propsDic = [[NSDictionaryalloc]initWithContentsOfFile:fileName];
[selfsetValuesForKeysWithDictionary:propsDic];
returnself;
}
returnnil;
}
网友评论