下面介绍一下沙箱的目录结构:
默认情况下,每个沙盒含有3个文件夹:Documents, Library 和 tmp和一个应用程序文件(也是一个文件)。因为应用的沙盒机制,应用只能在几个目录下读写文件
Documents:苹果建议将程序中建立的或在程序中浏览到的文件数据保存在该目录下,iTunes备份和恢复的时候会包括此目录
Library:存储程序的默认设置或其它状态信息;
Library/Caches:存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除
tmp:提供一个即时创建临时文件的地方。
iTunes在与iPhone同步时,备份所有的Documents和Library文件。
iPhone在重启时,会丢弃所有的tmp文件。
一整套读写
</pre>//创建管理类 NSFileManager * fm = [NSFileManager defaultManager];// 获得沙盒中的路径 NSString * docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];// 需要创建的文件路径 NSString * filePath = [docPath stringByAppendingPathComponent:DATABASENAME]; if (![fm fileExistsAtPath:filePath]) {// 获得原始的数据库文件路径; NSString * dbPath = [[NSBundle mainBundle] pathForResource:@"xyz" ofType:@"sqlite"]; NSError * error = nil; [fm copyItemAtPath:dbPath toPath:filePath error:&error]; if (error) { NSLog(@"错误:%@",error); } } </p><p class="artcon" style="text-indent: 2em; line-height: 20px;"></p><p class="artcon" style="text-indent: 2em; line-height: 20px;"><span style="font-family:Microsoft YaHei;font-size:12px;"></span><pre name="code" class="cpp">//1、获取程序的Home目录
NSString *homeDirectory = NSHomeDirectory();
NSLog(@"path:%@", homeDirectory);
//path:/Users/ios/Library/Application Support/iPhone Simulator/6.1/Applications/BF38C9E3-1A4A-4929-B5F2-3E46E41CC671
//2、获取document目录
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSLog(@"path:%@", path);
//path:/Users/ios/Library/Application Support/iPhone Simulator/6.1/Applications/BF38C9E3-1A4A-4929-B5F2-3E46E41CC671/Documents
//3、获取Cache目录
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSLog(@"path:%@", path);
//path:/Users/ios/Library/Application Support/iPhone Simulator/6.1/Applications/BF38C9E3-1A4A-4929-B5F2-3E46E41CC671/Library/Caches
//4、获取Library目录
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSLog(@"path:%@", path);
//path:/Users/ios/Library/Application Support/iPhone Simulator/6.1/Applications/BF38C9E3-1A4A-4929-B5F2-3E46E41CC671/Library
//5、获取tmp目录
NSString *tmpDir = NSTemporaryDirectory();
NSLog(@"path:%@", tmpDir);
//path:/Users/ios/Library/Application Support/iPhone Simulator/6.1/Applications/BF38C9E3-1A4A-4929-B5F2-3E46E41CC671/tmp/
在某目录下创建一个文件
4.1 、在document中创建一个文件目录
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"documentsDirectory%@",documentsDirectory);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *testDirectory = [documentsDirectory stringByAppendingPathComponent:@"test"];
// 创建目录
[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];