iOS沙盒与Bundle详解及文件操作

一、iOS沙盒机制:

        iOS应用程序只能在为该改程序创建的文件中读取文件,不可以去其它地方访问,此区域被成为沙盒,所以所有的非代码文件都要保存在此,例如图像,图标,声音,映像,属性列表,文本文件等。沙盒是系统为每一个应用程序生成的一个特定文件夹 ,文件夹的名字由十六进制数据组成,每一个应用程序的沙盒文件名都是不一样的,是由系统随机生成的。当应用程序被安装到设备上时,系统会为其创建一个家目录,这个家目录就是应用程序的沙盒。

  • 每个应用程序都有自己的存储空间
  • 应用程序不能翻过自己的围墙去访问别的存储空间的内容
  • 应用程序请求的数据都要通过权限检测,假如不符合条件的话,不会被放行

家目录下共有三个子目录:

1、Documents 目录:您应该将所有的应用程序数据文件写入到这个目录下,这个目录用于存储用户数据或其它应该定期备份的信息。

2、Library 目录:这个目录下有两个子目录:Caches 和 Preferences。

  • Caches目录用于存放应用程序专用的支持文件,保存应用程序再次启动过程中需要的信息,存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出后删除。
  • Preferences 目录包含应用程序的偏好设置文件。您不应该直接创建偏好设置文件,而是应该使用NSUserDefaults类来取得和设置应用程序的偏好。

3、tmp 目录:这个目录用于存放临时文件,保存应用程序再次启动过程中不需要的信息,iTunes不会备份和恢复此目录,此目录下文件可能会在应用退出后删除。

注意:iTunes在与iPhone同步时,备份所有的Documents和Library文件。iPhone在重启时,会丢弃所有的tmp文件。

获取沙盒主目录(即家目录):

<span style="font-size:12px;">NSString *path = NSHomeDirectory();</span>

沙盒下每个文件夹的路径:

1、获取Documents文件目录:

<span style="font-size:12px;">NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];</span>
//用firstobject取值是因为该方法一开始使用mac端OS X开发,对于PC端用户可以有多个用户,所以可以取到很多user的路径,但是该方法现在用于手机开发,手机端只有一个用户,所以获得的用户只有一个,lastobject也是可以的。
2、获取Library文件目录:


<span style="font-size:12px;">NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];</span>

  • 获取Library文件夹下的Caches文件目录:

<span style="font-size:12px;">NSString *cachesPath  = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];</span>

  • 获取Library文件夹下的Preferences文件目录:

NSString *cachesPath  = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];

3、获取tmp文件目录:

<span style="font-size:12px;">NSString *tempPath = NSTemporaryDirectory();</span>

注意:ios8之前,程序包和沙盒在同一个目录下,之后.app单独存储到一个独立的文件目录下。 .app 文件 readOnly。从appStore下载下来的是这个包,程序上传的时候也是这个包。

<span style="font-size:12px;">    // NSSearchPathDirectory 这个类是用来查找文件目录的
    //第一个参数:文件名称
    //第二个参数,确定搜索域
    //第三个参数:确定相对路径还是绝对路径。YES绝对,NO相对</span>

二、Bundle:

        Bundle简单地讲,就是一个内部结构按照标准规则组织的特殊目录。iOS的应用都是通过bundle进行封装的,对应的bundle类型是Application类型,平时我们通过Xcode编译出来的Target(即我们开发的应用),其实就是一个Application类型bundle,即一个文件夹!

        简单理解,就是资源文件包。我们将许多图片、XIB、文本文件组织在一起,打包成一个Bundle文件。方便在其他项目中引用包内的资源。

        Bundle是静态的,也就是说,我们包含到包中的资源文件作为一个资源包是不参加项目编译的。也就意味着,bundle包中不能包含可执行的文件。它仅仅是作为资源,被解析成为特定的二进制数据。

        mainBundle对应于应用程序文件归档或者应用程序的封包:一个以“.app”为扩展名并以应用程序名称为基本名的目录。

三、文件相关操作

1、文件删除

- (void)deleteFile {
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];

    NSString *imagePath = [cachesPath stringByAppendingPathComponent:@"iamge"];
    NSLog(@"%@",imagePath);
    //创建文件管理者
    NSFileManager *fileManager =  [NSFileManager defaultManager];
    //判断文件是否存在
    BOOL isExist = [fileManager fileExistsAtPath:imagePath];
    if (!isExist) {
        BOOL isSuccess = [fileManager createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:nil];
        NSLog(@"%@",isSuccess ? @"创建成功" : @"创建失败");
    }
    //删除文件
    if ([fileManager fileExistsAtPath:imagePath]) {
        BOOL isSucess = [fileManager removeItemAtPath:imagePath error:nil];
        NSLog(@"%@",isSucess ? @"删除成功" : @"删除失败");
    }
}

2、文件移动

- (void)moveFile {
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    
    NSString *imagePath = [cachesPath stringByAppendingPathComponent:@"iamge"];
    NSLog(@"%@",imagePath);
    //创建文件管理者
    NSFileManager *fileManager =  [NSFileManager defaultManager];
    //判断文件是否存在
    BOOL isExist = [fileManager fileExistsAtPath:imagePath];
    if (!isExist) {
        BOOL isSuccess = [fileManager createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:nil];
        NSLog(@"%@",isSuccess ? @"创建成功" : @"创建失败");
    }
    //删除文件
    //    if ([fileManager fileExistsAtPath:imagePath]) {
    //        BOOL isSucess = [fileManager removeItemAtPath:imagePath error:nil];
    //        NSLog(@"%@",isSucess ? @"删除成功" : @"删除失败");
    //    }
    //拷贝文件
    //把包中的plist文件拷贝到image文件夹下
    NSString *plistInBundlePath = [[NSBundle mainBundle] pathForResource:@"NB.plist" ofType:nil];
    NSString *nBPath = [imagePath stringByAppendingPathComponent:@"NB.plist"];
    // 拷贝,
    if (![fileManager fileExistsAtPath:nBPath]) {
        BOOL isSuccess = [fileManager copyItemAtPath:plistInBundlePath toPath:nBPath error:nil];
        NSLog(@"%@",isSuccess ? @"拷贝成功" : @"拷贝失败");
    }
    
    NSString *toPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
    BOOL isSuccess = [fileManager moveItemAtPath:nBPath toPath:[toPath stringByAppendingPathComponent:@"NB.plist"] error:nil];
    NSLog(@"%@",isSuccess ? @"移动成功" : @"移动失败");
}

3、字符串写入文件

- (void)writeToFile {
    //简单对象写入文件:字符串,数组,字典,二进制流 只有这些简单对象支持文件的写入
    //如果要写入的文件数据时数组,字典,必须要保证数组,字典中的数据 也是简单对象(如果是复杂对象,需要使用归档、反归档)
    //将字符串写入Documents文件夹下
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
    NSString *toPath = [documentsPath stringByAppendingPathComponent:@"string.txt"];
    NSString *string = @"string-string-string-";
    //第一个参数,要写入的文件路径,如果不存在文件,会自动创建    第二个参数,原子性,判断是否需要生成辅助文件,保护在多线程下安全    第三个参数,编码格式    第四个参数,错误信息
    NSError *error = nil;
    BOOL isSuccess = [string writeToFile:toPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    NSLog(@"%@",isSuccess ? @"写入成功" : @"写入失败");
    NSString *str = [NSString stringWithContentsOfFile:toPath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",str);
}

4、数组写入文件

- (void)writeArray {
    
    NSString *str = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject];
    NSString *toPath = [str stringByAppendingPathComponent:@"array.txt"];
    NSArray *array = @[@"123",@"123"];
    BOOL isSuccess = [array writeToFile:toPath atomically:YES];
    NSLog(@"%@",isSuccess ? @"写入成功" : @"写入失败");
    
    NSArray *arr = [NSArray arrayWithContentsOfFile:toPath];
    NSLog(@"%@",arr);

}

5、NSData写入文件

- (void)writeData {
    NSString *tempPath = NSTemporaryDirectory();
    NSString *toPath = [tempPath stringByAppendingPathComponent:@"data.txt"];
    NSString *string = @"datadata";
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    BOOL isSuccess = [data writeToFile:toPath atomically:YES];
    NSLog(@"%@",isSuccess ? @"成功" : @"失败");
    NSData *getData = [NSData dataWithContentsOfFile:toPath];
    NSString *str = [[NSString alloc] initWithData:getData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);
}

6、写入preference目录

- (void)writeToPreference {
    // NSUserDefaults 继承自NSObject ,单例通过kvc模式赋值
    //创建用户索引对象
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:100 forKey:@"money"];
    //立即同步操作      对preference中的文件进行修改后,立即同步
    [defaults synchronize];
    NSInteger money = [defaults integerForKey:@"money"];
    NSLog(@"%ld",money);
    [defaults setInteger:10000 forKey:@"MyMoney"];
    [defaults synchronize];
    
    NSInteger you = [defaults integerForKey:@"you"];
    NSLog(@"%ld",(long)you);
    if (money < 10) {
        NSLog(@"there is no money");
    } else {
        NSLog(@"-100");
        money -= 100;
        [defaults setInteger:40 forKey:@"money"];
        [defaults setInteger:1000 forKey:@"YourMoney"];
    }
    // NSUserDefaults 一般存储一些比较小的数据,大部分用来存数值
    
    //例子:判断用户是否第一次登陆
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    BOOL isFirst = [userDefault boolForKey:@"isFirst"];
    [userDefault setBool:YES forKey:@"isFirst"];
    [userDefault synchronize];
    if (!isFirst) {
        NSLog(@"第一次登陆");
    } else {
        NSLog(@"不是第一次登陆");
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值