看了博看文思的iOS数据持久化教学视频,感觉总结的很好,我也要自己把它敲出来才行啊。
iOS数据持久化分为四种方式:属性列表、对象归档、sqlite3、coredata
一、属性列表
属性列表就是使用plist文件来保存数据。我们先来创建一个plist文件,然后再写入数据读出数据
NSMutableDictionary *valueMuDic = [[NSMutableDictionary alloc]init];
[valueMuDic setObject:@"123" forKey:@"key1"];
[valueMuDic writeToFile:path atomically:YES];
[valueMuDic release]
1、创建plist:
(1)可以使用按command +N快捷键创建,或者File —> New —> New File,选择Mac OS X下的Property List
(2)使用代码创建
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [pathArray objectAtIndex:0];<span style="font-family: SimSun; ">//获取Document路径</span>
path = [path stringByAppendingPathComponent:@"test.plist"];
[[NSFileManager defaultManager]createFileAtPath:path contents:nil attributes:nil];//创建文件
2、写入plist:
NSMutableDictionary *valueMuDic = [[NSMutableDictionary alloc]init];
[valueMuDic setObject:@"123" forKey:@"key1"];
[valueMuDic writeToFile:path atomically:YES];
[valueMuDic release];
3、读取plist :
NSMutableDictionary *dic1 = [[NSMutableDictionary alloc]initWithContentsOfFile:path];
二、对象归档
1、创建Book类,增加两个属性方法作者和书名,还需要实现coding协议才能归档
</pre><pre code_snippet_id="380685" snippet_file_name="blog_20140606_7_1176789" name="code" class="objc">@interface Book : NSObject<NSCoding>
@property (nonatomic,copy)NSString *author;
@property (nonatomic,copy)NSString *name;
@end
2、实现coding协议
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.author forKey:@"author"];
[aCoder encodeObject:self.name forKey:@"name"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if(self)
{
self.author = [aDecoder decodeObjectForKey:@"author"];
self.name = [aDecoder decodeObjectForKey:@"name"];
}
return self;
}
@end
3、进行归档
@implementation Book
Book *book = [[Book alloc]init];
book.name = @"a big dream";
book.author = @"ABC";
[NSKeyedArchiver archiveRootObject:book toFile:@"/users/guodong/Desktop/aaa"];
4、读取归档
Book *book1 = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/users/guodong/Desktop/aaa"];
NSLog(@"%@ %@",book1.author,book1.name);
今天就先写这两个。