ios應(yīng)用常用的數(shù)據(jù)存儲方式
- plist(XML屬性列表歸檔)
- 偏好設(shè)置NSUserDefault
- NSKeydeArchiver歸檔(存儲自定義對象)
- SQLite3(數(shù)據(jù)庫,關(guān)系型數(shù)據(jù)庫,不能直接存儲對象,要編寫一些數(shù)據(jù)庫的語句,將對象拆開存儲)
- 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)建繼承基類模型的子類模型即可。