iOS沙盒机制

本文介绍了iOS中的沙盒机制,旨在提高应用程序的安全性。通过Mac的Finder可以查看Xcode模拟器中的沙盒目录,包括Documents、Library和tmp等子目录。文章还详细展示了如何通过代码获取沙盒路径,创建、读取和写入文件的方法,以及创建文件夹的步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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(@"文件夹创建失败.");

    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值