iOS 数据序列化,NSCoding, NSCoder
2016-04-14 22:55
148 查看
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];
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];
相关文章推荐
- iOS状态栏设置
- iOS 图形图像动画 Core Animation
- iOS彩票项目--第七天,初次读取json数据、KVC转模型技巧、运行时字典转模型以及初步对显示网页的操作并且跟踪标签
- iOS SDWebImage清理缓存数据
- Xcode 技巧充电篇
- iOS之SDWebImage清理缓存
- iOS--手势之谜
- ios图文混排
- iOS之JSON Model模型
- iOS tableViewCell自适应高度 第三发类库
- iOS Code Signing: 解惑
- 基于MVC项目iOS项目重构的思路
- [IOS]Core Data(数据建模与保存)
- 【iOS开发】二维码生成 二维码读取 (带Logo的二维码)
- iOS开发中的错误整理,重写的构造函数中,没有通过self调用
- 总结ios开发中,常用的工具CocoaPods
- 05 VoLTE - Signaling - Call Scenarios
- iOS拍照之后图片自动旋转90度解决办法
- iOS企业开发In House ipa发布流程
- ALAsset,ALAssetsLibrary,ALAssetsgroup常见属性及用法