此方法基本思路是:保存對(duì)象前利用反射機(jī)制獲得該對(duì)象的每個(gè)屬性,再轉(zhuǎn)化為字典,最后將字典寫入文件。
讀取對(duì)象時(shí)先將文件的內(nèi)容讀入字典,在利用KVC機(jī)制中的setValuesForKeysWithDictionary方法給每個(gè)屬性賦值。
本方法只要為原有的類添加兩個(gè)方法即可實(shí)現(xiàn)保存讀取。
注意:本方法需要導(dǎo)入”運(yùn)行時(shí)“頭文件 objc/runtime.h,屬性只能為對(duì)象類型
頭文件加入兩個(gè)方法聲明.
-(BOOL)wirteToFile:(NSString*)fileName;
-(instancetype)initFromFile:(NSString*)fileName;
實(shí)現(xiàn)文件:
-(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;
}