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.firstName forKey: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];
}