runtime +kvo實現(xiàn)快速歸檔 解檔操作

先看一個初始版的
<pre>`

  • (void)viewDidLoad {
    [super viewDidLoad];

    Person *person = [[Person alloc]init];
    person.name = @"ezreal";
    person.height = @"134";
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];

    NSString *path = [filePath stringByAppendingPathComponent:@"test.plist"];
    

    BOOL result = [NSKeyedArchiver archiveRootObject:person toFile:path];
    if (result) {
    NSLog(@"success");
    }else
    {
    NSLog(@"fail");
    }
    NSLog(@"%@",filePath);

}
`</pre>

<pre>`
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.height forKey:@"height"];
}

//當從文件中讀取一個對象的時候就會調(diào)用方法
//在該方法中說明如何讀取保存在文件中的對象

-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.height = [aDecoder decodeObjectForKey:@"height"];
}
return self;
}
`</pre>

runtime版本

<pre>`
// 返回self的所有對象名稱

  • (NSArray *)propertyOfSelf{
    unsigned int count = 0;

    // 1. 獲得類中的所有成員變量
    Ivar *ivarList = class_copyIvarList(self, &count);

    NSMutableArray *properNames =[NSMutableArray array];
    for (int i = 0; i < count; i++) {
    Ivar ivar = ivarList[i];

      // 獲得成員屬性名
      NSString *name = [NSString stringWithUTF8String:ivar_getName(ivar)];
      
    [properNames addObject:key];
    

    }
    free(ivarList);
    return [properNames copy];
    }

// 歸檔

  • (void)encodeWithCoder:(NSCoder *)enCoder{
    // 取得所有成員變量名
    NSArray *properNames = [[self class] propertyOfSelf];

    for (NSString *propertyName in properNames) {
    [enCoder encodeObject:[self valueForKey:propertyName] forKey:propertyName];
    }
    }

// 解檔

  • (id)initWithCoder:(NSCoder *)aDecoder{
    // 取得所有成員變量名
    NSArray *properNames = [[self class] propertyOfSelf];

    for (NSString *propertyName in properNames) {

      [self setValue:[aDecoder decodeObjectForKey:propertyName] forKey:propertyName];
    

    }
    return self;
    }

`</pre>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容