沙盒和简单的对象的写入和读取(预习)

沙盒:每一个iOS应用程序都会为自己创建一个文件系统目录,这个独立,封闭,安全的空间,叫做沙盒

沙盒是一个安全体系

特点:1.每个应用程序的活动范围都限定在自己的沙盒里

         2.不能随意跨越自己的沙盒去访问别的应用程序沙盒中的内容(iOS8 已经部分开放)

         3.应用程序向外请求或接受数据都需要经过权限认证

 

应用程序的沙盒目录会有三个文件夹 Documents ,Library(下面有Caches和Preferences目录),tmp

 

Document:保存应用运行时生成的需要持久化的数据 iTunes会自动备份该目录

// 获取Document 目录

    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSLog(@"%@",path);

    

    NSString *documentDirectory = [path objectAtIndex:0];

    NSLog(@"%@", documentDirectory);

    

   //获取tmp目录:保存应用运行时所需要的临时数据,使用完后再降相应的文件从该目录删除,没有运行时,系统也有可能清除该目录下的文件,iTunes不会同步该目录

    NSString *tmpDir = NSTemporaryDirectory();

    NSLog(@"%@", tmpDir);

    

    Library:存储程序的默认设置和其他状态信息

    //获取library目录

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

    NSString *pathLib = [paths objectAtIndex:0 ];

    NSLog(@"%@", pathLib);

    

    //获取library/Caches目录:存放缓存文件

    NSArray *path1 = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

    NSString *pathCaches = [path1 objectAtIndex:0];

    NSLog(@"%@", pathCaches);

    

    //获取library/Preferences目录:保存应用的所有偏好设置

    NSArray *path2 = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

    

    NSString *pathPre = [[path2 objectAtIndex:0] stringByAppendingPathComponent:@"Preferences"];

    NSLog(@"%@", pathPre);

    

    //获取应用程序的包路径

    NSString *imagePath = [NSBundle mainBundle].resourcePath;

    NSLog(@"%@", imagePath);

    

    //字符串对象写入文件

    //构造字符串对象

    NSString *strPath = [documentDirectory stringByAppendingString:@"/text.txt"];

    //构造字符串对象

    NSString *foo_str = @"this is a test";

    //字符串储存

    [foo_str writeToFile:strPath atomically:YES encoding:NSUTF8StringEncoding error:nil];

    

    //从文件中读取字符串对象

    NSString *str = [NSString stringWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil];

    NSLog(@"%@", str);

    

    //数组对象写入文件

    //构造数组对象的储存路径

    NSString *arrayPath = [documentDirectory stringByAppendingString:@"/array.plist"];

    // 构造数组对象

    NSArray *foo_array = @[@"hjp", @"hly", @"lcl"];

    //储存数组对象

    [foo_array writeToFile:arrayPath atomically:YES];

    

    NSArray *reultArray = [NSArray arrayWithContentsOfFile:arrayPath];

    NSLog(@"%@", reultArray);

    

posted @ 2016-02-15 23:56  陆齐铭。  阅读(345)  评论(0编辑  收藏  举报