自動解歸檔

ios應(yīng)用常用的數(shù)據(jù)存儲方式

  1. plist(XML屬性列表歸檔)
  2. 偏好設(shè)置NSUserDefault
  3. NSKeydeArchiver歸檔(存儲自定義對象)
  4. SQLite3(數(shù)據(jù)庫,關(guān)系型數(shù)據(jù)庫,不能直接存儲對象,要編寫一些數(shù)據(jù)庫的語句,將對象拆開存儲)
  5. Core Data(對象型的數(shù)據(jù)庫,把內(nèi)部環(huán)節(jié)屏蔽)
NSKeydeArchiver歸檔、NSKeyedUnarchiver解檔
@protocol NSCoding  

-  (void)encodeWithCoder:(NSCoder *)aCoder;  

-  (nullable instancetype)initWithCoder:(NSCoder *)aDecoder;  

@end

要想對對象進(jìn)行歸檔首先必須遵守NSCoding的這兩個協(xié)議, 在實(shí)現(xiàn)這個兩個方法的時候要注意key值和類型匹配,并且在類有十幾個屬性,或者更多的屬性的時候,我們需要寫多行代碼去實(shí)現(xiàn)。
Objective-C運(yùn)行時庫提供了非常便利的方法獲取其對象運(yùn)行時所屬類及其所有屬性,并通過KVC進(jìn)行值的存取,那么這里我們可以運(yùn)用objc/runtime+KVC的知識完成一個自動解歸檔的過程。

/**
歸檔
*/


- (void)encodeWithCoder:(NSCoder *)aCoder
{
    unsigned int outCount;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    for (int i = 0; i < outCount; i++)
    {
        objc_property_t property = properties[i];
        const char *name = property_getName(property);
        NSString* propertyName = [NSString stringWithUTF8String:name];
        [aCoder encodeObject:[self valueForKey:propertyName] forKey:propertyName];
    }
    
}

/**
解檔
*/


- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init])
    {
        unsigned int outCount;
        objc_property_t *properties = class_copyPropertyList([self class], &outCount);
        for (int i = 0; i < outCount; i++)
        {
            objc_property_t property = properties[i];
            const char *name = property_getName(property);
            NSString* propertyName = [NSString stringWithUTF8String:name];
            [self setValue:[aDecoder decodeObjectForKey:propertyName] forKey:propertyName];
        }

    }
    return self;
}

注:頭文件導(dǎo)入 #import <objc/runtime.h>

另外可以封裝一個基類模型實(shí)現(xiàn)這兩個方法,當(dāng)有需要時直接創(chuàng)建繼承基類模型的子類模型即可。

github:https://github.com/ChenZhiCN/CZModel

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

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

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