一万小时 / iOS下使用本地文件存储应用数据(NSBundle和NSDocumentDirectory)

远没到拼智商的时候

iOS下使用本地文件存储应用数据(NSBundle和NSDocumentDirectory)

2012-09-03 posted in [点滴技术] with tags: [iOS, 安全, and sandbox]

在iOS开发中经常会遇到用户数据持久化的问题,一个比较简单的方法是在用户的sandbox 运行环境下使用plist进行存储和读取,这里面有个最常遇到的问题就是有时发你 觉得自己的代码没有问题时,但是就是不能存储成功.

看下面的代码片断.

-(void) initManager{
NSString *path = [self dataFilePath];
self.credentials = [NSMutableDictionary dictionaryWithContentsOfFile:path];
}
-(NSString *) dataFilePath{
NSString *path = [[NSBundle mainBundle] pathForResource:kStoargeFileName ofType:@"plist"];
return path;
}
-(void)updateStorage:(NSDictionary *)data{
NSString *path = [self dataFilePath];
self.credentials = [NSMutableDictionary dictionaryWithDictionary:data];
NSLog(@"%@", self.credentials);
[self.credentials writeToFile:path atomically:YES];
}
view raw gistfile1.m hosted with ❤ by GitHub

乍一看没有任何问题,但是在执行中会发现数据永远都不能存储.

于是我们开始思考可能会是权限的问题,于是在google的帮助下,我们使用了下面的代码:

-(void) initManager{
NSString *path = [self dataFilePath];
self.credentials = [NSMutableDictionary dictionaryWithContentsOfFile:path];
}
-(NSString *)dataFilePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths objectAtIndex:0];
return [documentPath stringByAppendingPathComponent:kStoargeFileName];
}
-(void)updateStorage:(NSDictionary *)data{
NSString *path = [self dataFilePath];
self.credentials = [NSMutableDictionary dictionaryWithDictionary:data];
NSLog(@"%@", self.credentials);
[self.credentials writeToFile:path atomically:YES];
}
view raw gistfile1.m hosted with ❤ by GitHub

然后在执行时,一切都正常了!整个世界安静了.

作为目标是一流程序员的我们当然不甘于只知道how,我们更要知道why.

why

ios sandbox

阅读官方文档总是最好的办法, 请看苹果官方文档中关于文件结构的说明:

$home/AppName.app -> 这个就是我们上面代码片断1中的[NSBundle mainBundle],而这个目录是只读. 主要是为了安全考虑.

$home/Docuemnts/ -> 这个就是我们代码片断2中所指向的路径,而此目录正是为了存储应用的数据等信息, 所以在此目录下存储是非常合适.

其它目录说明参考苹果官方文档.

Top

Press q to hide the help

Key Action Key Action
Small Scroll j Scroll Down k Scroll Up
Big Scroll b Scroll to Bottom t Scroll to Top
Post Navigation n Next Post(if exists) p Previous Post(if exists)
Page Navigation h Go to Blog's Home Page a Go to Blog's Archive Page
Page Navigation c Go to Blog's Category Page ? Show this help
Misc s Go to Search Box q hide the help