标签:
IOS保存文件的其中一种形式是NSKeyedArchiver、NSKeyedUnarchiver归档:
以下内容以一个to-do lists软件为例,ChecklistItem为一个项目(数据模型),包含一个字符串text和一个BOOL标记checked,items是视图控制器的NSMutableArray,包含多个ChecklistItem,保存数据时以items为整体保存到.plist文件,读取则一样。
1.首先在数据模型的.h文件中实现协议<NSCoding>,例如:
@interface ChecklistItem : NSObject <NSCoding>
2.添加encode和decode方法(NSCoder归档和解档时会调用)
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.text forKey:@"Text"];
[aCoder encodeBool:self.checked forKey:@"Checked"];
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
if((self = [super init]))
{
self.text = [aDecoder decodeObjectForKey:@"Text"];
self.checked = [aDecoder decodeBoolForKey:@"Checked"];
}
return self;
}
3.获取app沙盒Document路径和保存的文件名
-(NSString *)documentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory;
}
-(NSString *)dataFilePath
{
return [[self documentsDirectory] stringByAppendingPathComponent:@"Checklists.plist"];
}
4.在视图控制器中实现保存和读取.plist文件的方法
-(void)saveChecklistItems
{
NSMutableData *data = [[NSMutableData alloc]init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
[archiver encodeObject:_items forKey:@"ChecklistItems"];
[archiver finishEncoding];
[data writeToFile:[self dataFilePath] atomically:YES];
}
-(void)loadChecklistItems
{
NSString *path = [self dataFilePath];
if([[NSFileManager defaultManager] fileExistsAtPath:path])
{
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
_items = [unarchiver decodeObjectForKey:@"ChecklistItems"];
[unarchiver finishDecoding];
}
else
{
_items = [[NSMutableArray alloc]initWithCapacity:20];
}
}
5.当视图从storyboard解档时,读取.plist文件(如果存在的话)
-(id)initWithCoder:(NSCoder *)aDecoder
{
if((self = [super initWithCoder:aDecoder]))
{
[self loadChecklistItems];
}
return self;
}
6.在需要保存数据的操作方法中(添加、删除、修改一个项目)调用保存数据方法
[self saveChecklistItems];
IOS学习之NSKeyedArchiver、NSKeyedUnarchiver归档
标签:
原文地址:http://www.cnblogs.com/guitarandcode/p/5449604.html