NSCoding
存與取
NSCoding是把數(shù)據(jù)存儲在iOS和Mac OS上的一種極其簡單和方便的方式,它把模型對象直接轉(zhuǎn)變成一個文件,然后再把這個文件重新加載到內(nèi)存里,并不需要任何文件解析和序列化的邏輯。如果要把對象保存到一個數(shù)據(jù)文件中(假設(shè)這個對象實現(xiàn)了NSCoding協(xié)議),你可以這樣做咯:
//存到本地
Book *book = [[Book alloc] init];
[NSKeyedArchiver archiveRootObject:book toFile:filePath];
//從本地取出
Book *theBook = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
如何寫遵循NSCoding協(xié)議的類
實現(xiàn)兩個方法- (void)encodeWithCoder:(NSCoder *)aCoder、- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder,舉個剛剛Book類的栗子:
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.title forKey:@"title"];
[aCoder encodeObject:self.author forKey:@"author"];
[aCoder encodeBool:self.isPublished forKey:@"isPublished"];
}
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self) {
self.title = [aDecoder decodeObjectForKey:@"title"];
self.author = [aDecoder decodeObjectForKey:@"author"];
self.isPublished = [aDecoder decodeBoolForKey:@"isPublished"];
}
return self;
}
NSSecureCoding
NSSecureCoding是NSCoding的變種,因為NSCoding畢竟不太安全,大部分支持NSCoding的系統(tǒng)對象都已經(jīng)升級到支持NSSecureCoding了,如AFNetworking的AFURLSessionManager,下面老衲舉個栗子:
存與取
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
[unarchiver setRequiresSecureCoding:YES];
//解碼
Foo *someFoo = [unarchiver decodeObjectForKey:NSKeyedArchiveRootObjectKey];
如何遵循協(xié)議
在原來encodeWithCoder和initWithCoder的基礎(chǔ)上增加supportsSecureCoding,如下
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.title forKey:@"title"];
[aCoder encodeObject:self.author forKey:@"author"];
[aCoder encodeBool:self.isPublished forKey:@"isPublished"];
}
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self) {
self.title = [aDecoder decodeObjectForKey:@"title"];
self.author = [aDecoder decodeObjectForKey:@"author"];
self.isPublished = [aDecoder decodeBoolForKey:@"isPublished"];
}
return self;
}
+ (BOOL)supportsSecureCoding{
return YES;
}
NSCopying
NSCopying是一個與對象拷貝有關(guān)的協(xié)議。如果想讓一個類的對象支持拷貝,就需要讓該類實現(xiàn)NSCopying協(xié)議。NSCopying協(xié)議中的聲明的方法只有一個- (id)copyWithZone:(NSZone *)zone。當(dāng)我們的類實現(xiàn)了NSCopying協(xié)議,通過類的對象調(diào)用copy方法時,copy方法就會去調(diào)用我們實現(xiàn)的- (id)copyWithZone:(NSZone *)zone方法,實現(xiàn)拷貝功能。比如AFN里對session的configuration進(jìn)行了拷貝:
- (instancetype)copyWithZone:(NSZone *)zone {
return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration];
}