iOS-沙盒机制及数据存储等操作

iOS的APP可以在自己的沙盒里读写文件,但是不可以访问其他APP的沙盒。每一个APP都是一个信息孤立的房间,这些房间就相当于一个沙盒,相互是不可以进行通信的,唯独可以通过URL Scheme。沙盒里面的文件可以是照片、声音文件、文件、属性列表等。

沙盒的根目录结构:DocumentLibrarytemp
1.Document:用于存储用户数据,iTunes备份和恢复的时候会包括此目录。所以。苹果建议将程序中建立的或在程序中浏览到的文件数据保存在该目录下。
2.Library:包含两个子目录:CachesPreferencesCaches用来存放用户需要换成的文件。Preferences是APP的偏好设置,可以通过NSUserDefaults来读取和设置。
3.tmp:用于存放临时文件,这个可以存放一些当APP退出后不需要再保存的文件。

获取沙盒路径
 //获取路径三种方法
 NSString *path = NSHomeDirectory();
 //拼接字符串
 NSString *documents = [path stringByAppendingString:@"/Documents"];
 //专业拼接路径
 NSString *str = [path stringByAppendingPathComponent:@"Documents"];
系统提供的方法获取Document路径
NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *strD = [array objectAtIndex:0];
NSLog(@"%@",strD);
获取library路径
NSArray *arrayL = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *strL = [arrayL objectAtIndex:0];
NSLog(@"%@",strL);
获取tmp路径
NSString *path = NSTemporaryDirectory();
NSLog(@"%@",path);
获取caches路径
NSArray *arrayC = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *strC = [arrayC objectAtIndex:0];
NSLog(@"%@",strC);
用NSUserDefaults对Preferences进行读取和设置
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
[user setObject:@"zhangsan" forKey:@"name"];
[user setObject:@"lisi" forKey:@"names"];
//将数据同步到沙盒的规定目录下(library下的preferences目录)
[user synchronize];

基本类型数据的存储和读取

  • 字符串存储、读取
- (void)saveString{
    //获取Document目录
    NSString *string = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //在沙盒文件下创建文件
    NSString *newPath = [string stringByAppendingString:@"/text.txt"];
    //要存入的内容
    NSString *name = @"UMR";
    //写入文件
    [name writeToFile:newPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
- (void)readingString{
    //获取路径
    NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *newPath = [str stringByAppendingString:@"/text.txt"];
    //读取数据
    NSString *string = [NSString stringWithContentsOfFile:newPath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",string);
}
  • 数组存储、读取
- (void)saveArray{
    //1.获取路径
    //获取目录
    NSString *string = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //在沙盒文件下创建文件
    NSString *newPath = [string stringByAppendingString:@"/array.plist"];
    //要存入的内容
    NSArray *array = @[@"zhangsan",@"lisi",@"wangwu"];
    //写入
    [array writeToFile:newPath atomically:YES];
    NSLog(@"%@",newPath);
}
- (void)readingArray{
    //获取路径
    NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *newPath = [str stringByAppendingString:@"/array.plist"];
    //读取数据
    NSArray *array = [NSArray arrayWithContentsOfFile:newPath];
    NSLog(@"%@",array);
}
  • 字典存储、读取
- (void)saveDictionary{
    //获取路径
    NSString *string = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *newPath = [string stringByAppendingString:@"/dictionary.plist"];
    //存储内容
    NSDictionary *dict = @{@"n1":@[@"1",@"2",@"3"],@"n2":@{@"a":@"d",@"s":@"g"},@"n3":@"uuummmrrr"};
    [dict writeToFile:newPath atomically:YES];
    NSLog(@"%@",newPath);
}
- (void)readingDictionary{
    //获取路径
    NSString *string = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *newPath = [string stringByAppendingString:@"/dictionary.plist"];
    //读取内容
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:newPath];
    NSLog(@"%@",dic);
}
  • data存储、读取
- (void)saveData{
    //获取路径
    NSString *string = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //存储路径
    NSString *newPath = [string stringByAppendingString:@"/data.plist"];
    //存储内容
    NSString *str = @"UMR";
    //将string转换成data
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    //写入文件夹
    [data writeToFile:newPath atomically:YES];
    NSLog(@"%@",newPath);
}
- (void)readingData{
    //获取路径
    NSString *string = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //存储路径
    NSString *newPath = [string stringByAppendingString:@"/data.plist"];
    //从文件读取data
    NSData *data = [NSData dataWithContentsOfFile:newPath];
    //将data转换成为string
    NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);
}
  • image存储 - 需转换为data进行存储和读取
- (void)saveImage{
    //获取路径
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //在文件路径下面创建该文件夹
    NSString *newPath = [path stringByAppendingString:@"/image.png"];
    //将.png转为data格式
    NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"name6.png"]);
//    NSData *imageD = UIImageJPEGRepresentation([UIImage imageNamed:@"name6.png"], 1); 如果是JPG格式的,后面的CGFloat为压缩系数;
    //将data文件写入文件夹
    [imageData writeToFile:newPath atomically:YES];
    NSLog(@"%@",newPath);
}
- (void)readingImage{
    //获取路径,获取文件
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *newPath = [path stringByAppendingString:@"/image.png"];
    NSData *imageData = [NSData dataWithContentsOfFile:newPath];
    //将data转为图片格式
    UIImage *image = [UIImage imageWithData:imageData];
    //获取 - 赋值
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(120, 120, 120, 120)];
    imageView.image = image;
    [self.view addSubview:imageView];
    NSLog(@"%@",newPath);
}

归档与反归档 - 复杂数据的沙盒存储

  • eg:先创建一个Person对象,声明相关属性
//归档必须遵守NSCoding协议
@interface Person : NSObject<NSCoding>
@property (nonatomic,strong) NSString *name;
@property (nonatomic,strong) NSString *gender;
@property (nonatomic,assign) NSInteger age;
@end```
 - 在.m文件中实现这两个NSCoding协议方法

@implementation Person
//对对象进行归档的时候调用

  • (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.gender forKey:@"gender"];
    [aCoder encodeInteger:self.age forKey:@"age"];
    }
    //对对象进行反归档的时候调用
  • (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super init]) {
    self.name = [aDecoder decodeObjectForKey:@"name"];
    self.gender = [aDecoder decodeObjectForKey:@"gender"];
    self.age = [aDecoder decodeIntegerForKey:@"age"];
    }
    return self;
    }
    @end```
  • 归档
- (void)saveData{
    Person *person = [[Person alloc] init];
    person.name = @"umr";
    person.gender = @"m";
    person.age = 18;
    //进行规档操作
    //1.创建一个NSMutableData来存储归档后的数据
    NSMutableData *Data = [[NSMutableData alloc] init];
    //2.创建归档器
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:Data];
    //3.进行归档
    [archiver encodeObject:person forKey:@"person"];
    //4.归档结束
    [archiver finishEncoding];
    //获取沙盒路径
    NSString *SDPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *newPath = [SDPath stringByAppendingString:@"/archiver.plist"];
    //写入文件
    [Data writeToFile:newPath atomically:YES];
    NSLog(@"%@",newPath);
}```
 - 反归档
  • (void)readData{
    //获取沙盒路径
    NSString *path = [[self documentPath] stringByAppendingString:@"/archiver.plist"];
    //获取数据
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSKeyedUnarchiver *Unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    Person *person1 = [Unarchiver decodeObjectForKey:@"person"];
    [Unarchiver finishDecoding];
    NSLog(@"%@ %ld %@",person1.name,person1.age,person1.gender);
    }```
- (NSString *)documentPath{
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}```
### - 对象数组的归档与反归档
  • (void)codeArray{
    //创建两个person对象
    Person *person1 = [[Person alloc] init];
    person1.name = @"huahua";
    Person *person2 = [[Person alloc] init];
    person2.name = @"UMR";

    存入数组 - 数组中的复杂对象必须遵守NSCoding协议,就可以直接对数组进行归档

    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:person1,person2, nil];
    //获取路径
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *path = [documentPath stringByAppendingPathComponent:@"array.plist"];
    NSLog(@"%@",path);
    //归档
    [NSKeyedArchiver archiveRootObject:array toFile:path];
    //反归档
    NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    // Person *per = arr[0];
    NSLog(@"%@",arr);
    }```
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,898评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,401评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,058评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,539评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,382评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,319评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,706评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,370评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,664评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,715评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,476评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,326评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,730评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,003评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,275评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,683评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,877评论 2 335

推荐阅读更多精彩内容