iOS开发--沙盒存储

4,122 阅读2分钟

沙盒简介

iOS中每个应用程序都有一个独立的文件夹,这个文件夹就是沙盒。沙盒用来存储app的本地文件,例如:音频、视频、图片文件等。并且每个app的沙盒都是独立的,即当前app没有权限访问其他app的沙盒,所以说沙盒存储较之更安全。

沙盒的层次结构

Documents: 存放长期使用文件
Library: 系统存放文件
tmp: 临时文件,APP重启,该目录下的文件会清空

沙盒路径

沙盒主目录:
homePath = NSHomeDirectory();

Documents目录:
[homePath stringByAppendingPathComponent:@"Documents"];

library目录:
[homePath stringByAppendingPathComponent:@"Library"];

tmp目录:
[homePath stringByAppendingPathComponent:@"tmp"]

路径其实就是一串字符串,stringByAppendingPathComponent将沙盒主目录路径拼接一个文件夹名,意思就是沙盒主目录下的各个分目录。

沙盒数据存储的三种方式

  • plist存储

plist文件存储一般都是存取字典和数组,直接写成plist文件,把它存到应用沙盒当中. 只有在ios当中才有plist存储,它是ios特有的存储方式.

// 存数据
- (void)saveForPlist {
    
    NSDictionary *dataDict = @{ @"name" : @"xiaoming",@"age" : @24};
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)[0];
  
    // 拼接一个文件名
    NSString *dict = [path stringByAppendingPathComponent:@"data.plist"];
    
    //dictPath为存储路径,Yes为线程保护
    [dataDict writeToFile:dictPath atomically:YES];
}
// 读数据
- (void)readForPlist {

    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)[0];
   
    // 数据路径
    NSString *dataPath = [path stringByAppendingPathComponent:@"data.plist"];
    NSDictionary *dataDict = [NSDictionary dictionaryWithContentsOfFile:path];
    NSLog(@"%@", dataDict);
}
  • Preference(偏好设置)

NSUserDefaults偏好设置存储,不需要路径,一般用于存储账号密码等信息。

// 存数据
- (void)saveForPreference {

    // 获取偏好设置对象
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    //存储数据
    [defaults setObject:@"xiaoming" forKey:@"name"];
    [defaults setInteger:24 forKey:@"age"];
    
    // 同步调用,立刻写到文件中,不写这个方法会异步,有延迟
    [defaults synchronize];    
}
//读数据
- (void)readForPreference {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    NSString *name = [defaults objectForKey:@"name"];
    NSInteger *age = [defaults integerForKey:@"age"];
    
    NSLog(@"%@-------%ld",name,age); 
}

偏好设置存储新的数据,不会覆盖原有文件,会在原文件里面续写。

  • NSKeyedArchiver(归档)

归档一般都是保存自定义对象的时候,使用归档.因为plist文件不能够保存自定义对象.如果一个字典当中保存有自定义对象,如果把这个字典写入到文件当中,它是不会生成plist文件的.

// 存数据:
- (void)saveForNSKeyedArchiver {

    Person *person = [[Person alloc] init];
    person.name = @"小明";
    person.age = 24;

    // 获取沙盒目录
    NSString *tempPath = NSTemporaryDirectory();
    NSString *filePath = [tempPath stringByAppendingPathComponent:@"Person.data"];
    NSLog(@"%@",tempPath);

    [NSKeyedArchiver archiveRootObject:per toFile:filePath];
}

// 读数据:
- (void)readForNSKeyedArchiver {

    // 获取沙盒目录
    NSString *tempPath = NSTemporaryDirectory();
    NSString *filePath = [tempPath stringByAppendingPathComponent:@"Person.data"];

    Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    NSLog(@"%@-----%li",per.name,per.age);
}