iOS学习8:iOS沙盒(sandBox)机制(二)之沙盒文件操作

一、在沙盒中写文件

在沙盒目录的Documents文件夹下添加一个plist文件,添加图片等方法相同

// 获取Documents文件夹目录
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

// 设定plist的路径
 [rootPath stringByAppendingPathComponent:@"new.plist"];

// 然后在plist中写入内容
NSString *error;
// 序列化一个值“OK”
id plist = [NSPropertyListSerialization dataFromPropertyList:@"OK" format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];

if(plist) {
        NSLog(@"No error creating XML data.");
        [plist writeToFile:plistPath atomically:YES];
    }
    else {
        NSLog(@"%@",error);
        [error release];
    }
运行后在Documents文件夹下将看到一个new.plist文件

文件中有一个值OK,也可添加数组,字典等相关类型的内容,只需将上文中的“OK”换成一个(id)类型的值即可

二、拷贝文件到沙盒目录下

下面拷贝一个public.xml文件至document路径下,也可拷贝其他文件,只需将文件名和类型对应即可,尤其是database文件,一定要拷贝至沙盒才能使用。此文件不能是电脑中的文件,必须加入工程的Bundle中

// 获取Documents路径
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) lastObject];

    // 设定要拷贝文件的路径及名称
    NSString *xmlSandBoxPath = [documentsPath stringByAppendingPathComponent:@"public.xml"];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    // 判断文件是否已经存在
    BOOL isExisting = [fileManager fileExistsAtPath:xmlSandBoxPath];

    if (!isExisting) {

        // 本地无此文件,则将此文件拷贝到本地目录。
        NSString *xmlFilePath = [[NSBundle mainBundle] pathForResource:@"public" ofType:@"xml"];
        NSError *err;
        // 将Bundle中的文件拷贝至沙盒目录下
        [fileManager copyItemAtPath:xmlFilePath toPath:xmlSandBoxPath error:&err];
    }
操作之后,Documents路径下就有这个文件了

转载于:https://my.oschina.net/joanfen/blog/159136

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值