IOS沙盒机制(sandbox)

首先我们来认识一下沙盒,沙盒就是每一个app对应的一块存储空间。
沙盒中有下列文件夹
Documents:文档 最常打交道的目录 iTunes会备份和恢复此文件夹的内容
Library/Caches : 缓存文件夹 用来保存缓存数据 不会备份和恢复
Library/Preferences:用户偏好设置 iTunes会备份和恢复此文件夹的内容
tmp:临时文件夹 存放临时文件 不会备份和恢复 此文件夹内容会不定时清除
下面我们通过代码来看一下沙盒的使用

NSString *homePath = NSHomeDirectory();
    NSLog(@"沙箱根目录:%@",homePath);

    //获取Documents路径两种方法
    NSString *documentsPath1 = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *documentsPath2 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
    NSLog(@"%@   %@",documentsPath1,documentsPath2);

    //获取缓存文件夹路径
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];

    //获取临时文件夹路径
    NSString *tmpPath = NSTemporaryDirectory();
    NSLog(@"缓存:%@ 临时:%@",cachePath,tmpPath);


    //往document中写.txt
    NSString *text = @"过年好!";
    NSString *path = [documentsPath1 stringByAppendingPathComponent:@"abc.txt"];
    [text writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];

    //往document中写.plist plist中存放数组
    NSString *filePath = [documentsPath1 stringByAppendingPathComponent:@"names.plist"];
    NSArray *names = @[@"a",@"b",@"c"];
    [names writeToFile:filePath atomically:YES];

输出结果如下:
这里写图片描述
下面我们复制documents的地址,通过finder前往当前目录,看一下plist文件,还有txt文件是否写入。结果如图:
这里写图片描述
对于plist文件读写,还有不理解的朋友请参考这篇微博:
http://blog.csdn.net/lee727n/article/details/70303766

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值