1、把需要保存的信息已plist文件形式保存在本地,即写入沙盒:
/**
* 写入本地(plist文件)
*/
- (void)saveArray
{
// 1.获得沙盒根路径
NSString *home = NSHomeDirectory();
// 2.document路径
NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
// 3.新建数据
NSDictionary *dict = @{@"haha":@"11",
@"hehe":@"12",
@"huhu":@"13",
@"gogo":@"14"
};
NSString *filepath = [docPath stringByAppendingPathComponent:@"data.plist"];
[dict writeToFile:filepath atomically:YES];
}
其中Decuments是沙盒固定路径,data.plist是自己取的要保存的文件的名字;
2、当需要拿出保存的信息的时候,读取保存在本地的plist文件:
/**
* 读取写入本地的plist文件
*/
- (IBAction)read {
// 1.获得沙盒根路径
NSString *home = NSHomeDirectory();
// 2.document路径
NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
// 3.文件路径
NSString *filepath = [docPath stringByAppendingPathComponent:@"data.plist"];
// 4.读取数据
NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filepath];
NSLog(@"%@", dic);
}
3、有时保存在本地的文件信息不是最新时,需要删除上次保存在本地的文件,然后重新保存的最新的信息在本地:
/**
* 删除保存在本地的plist文件的数据
*/
- (void)remove{
// 1.获得沙盒根路径
NSString *home = NSHomeDirectory();
// 2.document路径
NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
// 3.文件路径
NSString *filepath = [docPath stringByAppendingPathComponent:@"data.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:filepath error:nil];
}
这样就完成了文件的本地存储。
对于小文件的存储,减少了用数据库存储的麻烦,以plist文件存储,轻便、快捷,操作简单。
有时候对于网络数据的缓存,如果数据不是很打的话,也是可以用plist文件存储的。
原文:http://www.cnblogs.com/h-tao/p/5226400.html