ios 沙盒 NSCoding 归档 数据存储
来源:互联网 发布:淘宝网被冻结怎么办 编辑:程序博客网 时间:2024/05/16 08:57
转自:http://www.maxiaoguo.com/clothes/232.html
NSCoding 跟其他存储方式略有不同,他可以存储对象
对象存储的条件是: 对象需要遵守 NSCoding 协议存储的时候需要 调用 encodeWithCoder 方法
读取的时候需要调用initWithCoder 方法
[NSKeyedArchiver archiveRootObject:stu toFile:path]; 存储
NSKeyedUnarchiver unarchiveObjectWithFile:path 读取
对象代码
#import <Foundation/Foundation.h>@interface MJStudent : NSObject <NSCoding>@property (nonatomic, copy) NSString *no;@property (nonatomic, assign) double height;@property (nonatomic, assign) int age;@end
#import "MJStudent.h"@interface MJStudent() @end@implementation MJStudent/** * 将某个对象写入文件时会调用 * 在这个方法中说清楚哪些属性需要存储 */- (void)encodeWithCoder:(NSCoder *)encoder{ [encoder encodeObject:self.no forKey:@"no"]; [encoder encodeInt:self.age forKey:@"age"]; [encoder encodeDouble:self.height forKey:@"height"];}/** * 从文件中解析对象时会调用 * 在这个方法中说清楚哪些属性需要存储 */- (id)initWithCoder:(NSCoder *)decoder{ if (self = [super init]) { // 读取文件的内容 self.no = [decoder decodeObjectForKey:@"no"]; self.age = [decoder decodeIntForKey:@"age"]; self.height = [decoder decodeDoubleForKey:@"height"]; } return self;}@end
保存读取
- (IBAction)save { // 1.新的模型对象 MJStudent *stu = [[MJStudent alloc] init]; stu.no = @"42343254"; stu.age = 20; stu.height = 1.55; // 2.归档模型对象 // 2.1.获得Documents的全路径 NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; // 2.2.获得文件的全路径 NSString *path = [doc stringByAppendingPathComponent:@"stu.data"]; // 2.3.将对象归档 [NSKeyedArchiver archiveRootObject:stu toFile:path];}- (IBAction)read { // 1.获得Documents的全路径 NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; // 2.获得文件的全路径 NSString *path = [doc stringByAppendingPathComponent:@"stu.data"]; // 3.从文件中读取MJStudent对象 MJStudent *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; NSLog(@"%@ %d %f", stu.no, stu.age, stu.height);}
0 0
- ios 沙盒 NSCoding 归档 数据存储
- 归档 NSCoding 数据存储小结《IOS编程》 读后总结
- iOS 数据存储 归档普通对象 NSCoding NSKeyedArchiver
- NSCoding归档数据持久化存储
- 数据存储之归档-NSCoding协议
- 【iOS开发-存储】使用NSCoding归档和反归档
- iOS-NSCoding归档
- ios-day12-04(ios开发中数据存储之NSKeyedArchiver归档(NSCoding)、普通对象如何归档、普通对象的子类如何归档)
- iOS数据存储之--NSCoding
- NSCoding协议,遵循了NSCoding协议的数据模型,就可以利用归档进行数据存储了
- iOS归档存储数据
- iOS 归档(NSKeyedArchiver + NSCoding)
- 数据存储(NSCoding)
- iOS数据存储之---归档
- ios数据存储之归档
- iOS nscoding 实现归档解档
- 数据缓存——NSKeyedArchiver归档(NSCoding)
- <NSCoding>存储数据 archivedDataWithRootObject unarchiveObjectWithData
- fstream,ifstream,ofstream 详解与用法
- ios tableview 那些事(二十三) 解决headerView不随cell一起滚动的问题
- 常用的电脑快捷键大全
- i386 错误
- 部门表数据
- ios 沙盒 NSCoding 归档 数据存储
- 自定义控件:SlidingUpPanelLayout
- Android中的Context 类的理解和它的应用
- java环境变量配置(windows7)
- PHP的namespace关键字小小的疑点解惑
- python爬duitang的摄影类图片
- 由ORA-28001同时带出ORA-28000的解决办法
- OCP-1Z0-051 第102题 TO_DATE,TO_CHAR,TO_NUMBER函数的用法
- 异步简单例子