iOS可以利用NSKeyedArchiver类将对象序列化成NSData存储在磁盘上,但前提是该对象所属的类必须遵从NSCoding协议。
NSCoding协议包含两个方法,要序列化的类必须实现它们
- (void)encodeWithCoder:(NSCoder *)aCoder; //序列化的时候将数据encode (将数据编码)
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder; // 反序列化的时候将数据decode (将数据解码)
例:
@interface MyEntity: NSObject<NSCoding>
@property (nonatomic, strong) NSString *name;
@end
@implementation MyEntity
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder.encodeObject:self.name forKey:@"name"];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
[self.name = aDecoder.decodeObjectForKey:@"name"];
}
@end
此时,MyEntity类即可被序列化,序列化过程:
MyEntity *myEntity = [[MyEntity alloc] init];
NSData *myEntityData = [NSKeyedArchiver archivedDataWithRootObject:myEntity];
[[NSUserDefaults standardUserDefatults] setObject:myEntityData forKey:@"myEntityDataKey"];
反序列化过程:
NSData *myEntityDataOnDisk = [[NSUserDefaults standardUserDefaults] objectForKey:@"myEntityDataKey"];
MyEntity *myEntityOnDisk = [NSKeyedUnarchiver unarchiveObjectWithData:myEntityDataOnDisk];