iOS沙盒路径的查看和使用

iphone沙箱模型的有四个文件夹:documents,tmp,app,Library

1、Documents 目录:您应该将所有的应用程序数据文件写入到这个目录下。这个目录用于存储用户数据或其它应该定期备份的信息。
2、AppName.app 目录:这是应用程序的程序包目录,包含应用程序的本身。由于应用程序必须经过签名,所以您在运行时不能对这个目录中的内容进行修改,否则可能会使应用程序无法启动。
3、Library 目录:这个目录下有两个子目录:Caches 和 Preferences
Preferences 目录:包含应用程序的偏好设置文件。您不应该直接创建偏好设置文件,而是应该使用NSUserDefaults类来取得和设置应用程序的偏好.
Caches 目录:用于存放应用程序专用的支持文件,保存应用程序再次启动过程中需要的信息。
4、tmp 目录:这个目录用于存放临时文件,保存应用程序再次启动过程中不需要的信息。

获取这些目录路径的方法:
1,获取主目录路径的函数:

NSString *homeDir = NSHomeDirectory();


2,获取Documents目录路径的方法:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];


3,获取Caches目录路径的方法:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];


4,获取tmp目录路径的方法:

NSString *tmpDir = NSTemporaryDirectory();

5,获取应用程序程序包中资源文件路径的方法:
例如获取程序包中一个图片资源(apple.png)路径的方法:

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@”apple” ofType:@”png”];
UIImage *appleImage = [[UIImage alloc] initWithContentsOfFile:imagePath];

6,向目录中写入文件

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    if (!docDir) {
        NSLog(@"Documents 目录未找到");        
    }
    NSArray *array = [[NSArray alloc] initWithObjects:@"内容",@"content",nil];
    NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];
    [array writeToFile:filePath atomically:YES];

注:我们在真机上也运行一下,把文件写入,下一步从真机上把内容读取出来。

写入输入 array ,里面是两个字符串,一会我们读出来打印。

写入我们在程序沙盒目录下看到文件 testFile.txt

 

打开文件看到的内容是这样的,是个xml格式的plist文件,数据格式保存了内容。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <string>内容</string>
    <string>content</string>
</array>
</plist>

7,读取文件

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *filePath = [docDir stringByAppendingPathComponent:@"testFile.txt"];
    NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath];
    NSLog(@"%@", array);

打印结果:

"U5185U5bb9",
    content

把上面的文件解析后,把内容打印出来了。 

真机上读取并打印文件路径

真机上也能写入和打印。

 

参考:http://www.gowhich.com/blog/188

http://blog.csdn.net/totogo2010/article/details/7670417

原文地址:https://www.cnblogs.com/endtel/p/4961821.html