iOS沙盒是apple公司的为了提高程序的安全性而做出的硬性规定:应用程序只能访问系统为它创建的目录里的文件。
可以通过mac的finder来查看xcode模拟器里的沙盒:
1. 操作步骤:finder->前往-> 前往文件夹(下图示):
2.在弹出的对话框中些如~/Library或~/资源库,点击"前往":
3. 在弹出的资源库中找到Application Support-->iphone simulator并执行下图的操作:
上图选中的一长串16进制32位长度的文件夹下每个app的沙盒,里面一般包含三个文件夹和一个.app:
其中document用来保存程序运行过程中产生的文件,library用于保存程序的默认设置,tmp及时一些临时文件。app格式文件前面是一个禁止符号,英文mac上不能运行ios的程序。你可以通过鼠标右键点击.app文件,然后点击下拉列表的“显示包含内容”,你可以看到诸如下图所示的内容:
没错,这个文件就是我们平常经常提到的bundle,比如说我想获取info.plist(见上图)文件路径:
NSString *plistPath = [[NSBundlemainBundle]pathForResource:@"info"ofType:@"plist"];
下面是一些通过代码获取沙盒里文件夹路径及
创建文件和读写文件的操作:
//bundle 名字
NSString *bundle = [[NSBundlemainBundle]bundleIdentifier];
//获取沙盒的根路径:
NSString *dirHome = NSHomeDirectory();
NSLog(@"root_path:%@", dirHome);
//获取Document路径:
NSArray *docPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docDir = [docPath objectAtIndex:0];
NSLog(@"document_path:%@", docDir);
//获取Library路径
NSArray *LibPath =NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
NSString *LibDir = [LibPath objectAtIndex:0];
NSLog(@"LibraryPath:%@", LibDir);
//获取tmp路径
NSString *tmpDirectory = NSTemporaryDirectory();
NSLog(@"tmpPath:%@", tmpDirectory);
//创建文件夹
NSFileManager *fileManger = [NSFileManagerdefaultManager];
NSString *directory = [docDir stringByAppendingString:@"/hello"];
BOOL bRet = [fileMangercreateDirectoryAtPath:directorywithIntermediateDirectories:YESattributes:nilerror:nil];
if (bRet) {
//创建文件
NSString *filepath = [directory stringByAppendingString:@"/test.txt"];
BOOL bSuccess = [fileManger createFileAtPath:filepath contents:nilattributes:nil];
if(bSuccess){
NSLog(@"文件创建成功.");
//写文件数据:
NSString *content = @"文件文本内容!";
BOOL bWrite = [contentwriteToFile:filepathatomically:YESencoding:NSUTF8StringEncodingerror:nil];
if(bWrite){
NSStringEncoding encode = NSUTF8StringEncoding;
//读文件数据:
NSString *readContent = [NSStringstringWithContentsOfFile:filepathusedEncoding:&encode error:nil];
NSLog(@"readContent:%@", readContent);
}
}
else{
NSLog(@"文件创建失败.");
}
}
else{
NSLog(@"文件夹创建失败.");
}