NSCoding is a protcol that you can implement on your data classes to support encoding and decoding your data into a data buffer, which can then be persisted to disk.數據庫
若是想把自定義的對象持久化(存到硬盤),或者用於網絡傳輸。須要先將自定義對象序列化成NSData網絡
若是自定義對象要想轉成NSData,須要服從NSCoding協議。並實現其中的兩個方法。ui
iOS6中,蘋果引入了一個新的協議,是基於NSCoding的,叫作NSSecureCoding。NSSecureCoding和NSCoding是同樣的,除了在解碼時要同時指定key和要解碼的對象的類,若是要求的類和從文件中解碼出的對象的類不匹配,NSCoder會拋出異常,告訴你數據已經被篡改了。
大部分支持NSCoding的系統對象都已經升級到支持NSSecureCoding了atom
持久化三個常見方法spa
無論是哪種方案,都不可能直接存儲用戶自定義的對象,因此須要將自定義的對象序列化成NSData,才能持久化。code
須要用到的時候,就用數據庫中取出,而後反序列化,恢復成對象orm
Democdn
// Foo.h
@interface Foo : NSObject <NSSecureCoding>
@property (nonatomic, copy) NSString *bar;
@property (nonatomic, assign) float baz;
@end
複製代碼
// Foo.m
#import "Foo.h"
static NSString * const kBar = @"kBar";
static NSString * const kBaz = @"kBaz";
@implementation Foo
- (void)encodeWithCoder:(nonnull NSCoder *)aCoder {
[aCoder encodeObject:_bar forKey:kBar];
[aCoder encodeFloat:_baz forKey:kBaz];
}
- (nullable instancetype)initWithCoder:(nonnull NSCoder *)aDecoder {
if (self = [super init]) {
self.bar = [aDecoder decodeObjectForKey:kBar];
self.baz = [aDecoder decodeFloatForKey:kBaz];
}
return self;
}
+ (BOOL)supportsSecureCoding
{
return YES;
}
-(NSString *)description{
return [NSString stringWithFormat:@"bar:%@ ; baz:%f",self.bar, self.baz];
}
@end
複製代碼
Foo *foo = [[Foo alloc] init];
foo.bar = @"祈求者Kael";
foo.baz = 24;
NSError *error0;
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:foo requiringSecureCoding:YES error:&error0];
NSLog(@"data --- %@", data);
NSError *error1;
Foo *foo1 = [NSKeyedUnarchiver unarchivedObjectOfClass:[Foo class] fromData:data error:&error1];
NSLog(@"foo1 = %@", foo1);
複製代碼
2019-05-23 20:28:06.252195+0800 NSCodingDemo[1081:41952] data --- <62706c69 73743030 d4010203 04050616 17582476 65727369 6f6e5824 6f626a65 63747359 24617263 68697665 72542474 6f701200 0186a0a4 07080f10 55246e75 6c6cd309 0a0b0c0d 0e546b42 6172546b 42617a56 24636c61 73738002 2241c000 00800367 79486c42 8005004b 00610065 006cd211 1213145a 24636c61 73736e61 6d655824 636c6173 73657353 466f6fa2 1315584e 534f626a 6563745f 100f4e53 4b657965 64417263 68697665 72d11819 54726f6f 74800108 111a232d 32373c42 494e535a 5c616372 77828b8f 929badb0 b5000000 00000001 01000000 00000000 1a000000 00000000 00000000 00000000 b7>
2019-05-23 20:28:06.252538+0800 NSCodingDemo[1081:41952] foo1 = bar:祈求者Kael ; baz:24.000000複製代碼