save Objects to Files
来源:互联网 发布:mac新系统sierra 编辑:程序博客网 时间:2024/04/28 19:32
1。将对象保存到磁盘文件中:该对象必须实现<NSCoding>协议
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (instancetype)initWithCoder:(NSCoder *)aDecoder;
NSKeyedArchiver:归档、存档,将对象读入(保存到磁盘文件中)
NSKeyedUnarchiver:解档,将对象取出(从磁盘文件中取出)
e.g.
@interface Person : NSObject <NSCoding>
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;
@end
//=============
#import "Person.h"
NSString *const kFirstNameKey = @"FirstNameKey";
NSString *const kLastNameKey = @"LastNameKey";
@implementation Person
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.firstNameforKey:kFirstNameKey];
[aCoder encodeObject:self.lastName forKey:kLastNameKey];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self != nil){
_firstName = [aDecoder decodeObjectForKey:kFirstNameKey];
_lastName = [aDecoder decodeObjectForKey:kLastNameKey];
}
return self;
}
@end
//============
-(void)actionSave{
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"steveJobs.txt"];
/* 初始化对象 */
Person *steveJobs = [[Person alloc] init];
steveJobs.firstName = @"Steven";
steveJobs.lastName =@"Jobs";
/* 归档 */
[NSKeyedArchiver archiveRootObject:steveJobs toFile:filePath];
/* 解档*/
Person *cloneOfSteveJobs = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
if (cloneOfSteveJobs !=nil) {
NSLog(@"Person:first Name:%@,last Name:%@",cloneOfSteveJobs.firstName,cloneOfSteveJobs.lastName);
}
/* 删除归档时的文件 */
NSFileManager *fileManager = [[NSFileManager alloc] init];
[fileManager removeItemAtPath:filePath error:nil];
}
- save Objects to Files
- Mapping Objects to XML Files using Java 5 Annotations
- Save Web Pages or Parts to Client-Side Files
- Android Studio -- Could not save project!: Unable to save project files.不能保存项目,报错解决办法
- How to copy all view private files and Derived objects between views
- How to copy all view private files and Derived objects between views
- Export Xellerate configuration objects to XML files from the command-line
- Save results to different files when executing multi SQL statements in DB Query Analyzer 7.01
- To Save Or Not To Save?
- 第一章: Introduction to Objects
- LINQ to Objects 学习
- Linq to Objects
- LINQ to Objects
- Introduction to Schema Objects
- LINQ to Objects<1>
- LINQ to Objects(2)
- Introduction to Objects
- Introduction To Objects
- Android Design 的缺陷
- Android-onInterceptTouchEvent()和onTouchEvent()总结
- 花开的时候最珍贵
- technology point
- 异常分享
- save Objects to Files
- QT5.2.0 + OpenCV2.4.6 + win7 终于成功!!!
- 编译原理学习笔记10——(野火烧不尽再递归下降—— E → E+T | T从上向下程序)——2014_1_26
- 在windows批处理脚本中实现循环计数。
- iOS - UIButton(UIEdgeInsets)/设置button上的文字和图片 在定义位置
- XHR(XMLHttpRequest)与Linux下的CGI交互
- zxing
- 绝对精彩的马字成语接龙40龙
- 顺序线性表和单链表的插入,删除操作