文件操作

  • NSUserDefault:保存少量的数据(几张的图片,字符串,小量的数组 字典 某个对象)
  • 文件:(图片、视频)一个资源就是一个文件(创建文件 写入数据 读取文件 删除文件 copy)
  • 数据库SQLite3:是用C语言进行编写的,不能储存OC或者swift数据而CoreData则可以
  • CoreData

iOS的沙盒机制(sandbox)#

iOS应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒,所以所有的非代码文件都要保存在此,例如图像,图标,声音,映像,属性列表,文本文件等。

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

通过这张图只能从表层上理解sandbox是一种安全体系,应用程序的所有操作都要通过这个体系来执行,其中核心内容是:sandbox对应用程序执行各种操作的权限限制。

文件操作_第1张图片
沙盒机制

应用程序的沙盒
1.获取应用程序允许用户操作的Document路径

 NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

2.创建文件的路径

 NSString * filePath = [docPath stringByAppendingString:@"/name"];
 NSString * filePath = [docPath stringByAppendingPathComponent:@"name"];

3.判断文件是否存在

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    //存在
}

4.创建文件

[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];

5.写入数据 转化成二进制

 NSData * imageData = UIImagePNGRepresentation(image);
 [imageData writeToFile:filePath atomically:YES];

6.二进制转图片

 NSError * errMsg = nil;
 NSData * data = [NSData dataWithContentsOfFile:filePath options:NSDataReadingUncached error:&errMsg];
 if (errMsg) {
 NSLog(@"%@",errMsg);
            return;
        }
        UIImage * img = [UIImage imageWithData:data];

7.创建文件

    if (![[NSFileManager defaultManager]fileExistsAtPath:filePath]) {
        [[NSFileManager defaultManager]createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }

8.删除文件夹

 if ([[NSFileManager defaultManager]fileExistsAtPath:filePath]) {
     [[NSFileManager defaultManager]removeItemAtPath:filePath error:nil];
 }

你可能感兴趣的:(文件操作)