您的位置:首页 > 移动开发 > IOS开发

iOS 沙盒 数据持久化

2015-12-10 18:14 453 查看
注意在这个笔记里有部分路径为方法,需要自己定义,在这里一定要熟练使用获取文件夹路径以及路径的拼接

数据持久化

什么是数据持久化 : 数据的永久存储

为什么要做数据持久化:存储在内存中的数据,程序关闭,内存释放,数据丢失。这种数据是临时的。

数据持久化的本质:数据保存成文件,存储到程序的沙盒里

沙盒机制

1.每个应用程序位于文件系统的严格限制部分

2.每个应用程序只能为该程序创建的文件系统中读取文件

3.每个应用程序在iOS系统中内都放在了统一的文件夹目录下

4.沙盒的本质就是一个文件夹,名字是随机分配的

沙盒

本质上就是一个文件夹。沙盒是iOS平台,针对每一款安装的应用在本地生成的文件。名字随机产生,应用之间不能相互访问对方内的文件内容

沙盒构成

Documents:存储存储数据持久化的文件,想长久存放的数据在该文件夹下,但该文件夹不能存放过多内容,否则,上线会被拒

Library

LIbrary/Caches 存放缓存图片,下载的视频 音频 图片等

LIbrary/Preference :存放用户的偏好设置,是否第一次登陆,用户名,密码

tmp: 临时文件夹,存放临时文件,比如:下载zip压缩包

1.打印沙盒路径

NSString *homepath = NSHomeDirectory();

NSLog(@”%@”,homepath);

//2.应用程序的包路径
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSLog(@"%@",bundlePath);


//3.获取沙盒文件夹下documents文件夹的路径

01)NSDocumentDirectory :我们要查找的文件夹

02参数:查找的范围 NSUserDomainMask 在用户域中查找

03参数:要不要显示详细的路径

/*该方法之前是os X平台下的,对应os X平台下的,可以获取的是所有用户的文件夹路径,而对于iOS平台,用户只有一个,所以取得路径只有一个*/


//4.获取沙盒文件夹下Library文件夹路径

NSString * library = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)lastObject];

//5.获取沙盒文件夹下tmp文件夹路径
NSString *tmpPath =  NSTemporaryDirectory();//专门的路径

//6.获取沙盒文件夹下LIbrary文件夹下Caches文件夹路径
NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

//获取包中资源的路径
[[NSBundle mainBundle] pathForResource:@"资源名" ofType:@"资源类型"];


数据持久化方式之一

WriteToFile:….

写入文件 只支持简单对象:NSString NSArray NSDictionary NSData及其子类

数组中的元素也必须是对应的类型

//字符串的写入

//1.获取文件路径

NSString *stringFile = [self stringFilePath];

//写入文件

BOOL isSuccess = [self.TF1.text writeToFile:stringFile atomically:YES encoding:NSUTF8StringEncoding error:nil];

NSLog(@”%@”,isSuccess ?@”写入成功”:@”失败”);

//字符串的读取

//获取文件路径

NSString *strPath = [self stringFilePath];

//根据路径读取内容

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

self.TF2.text = string;

-(NSString *)stringFilePath {

//1获取Documents文件夹路径

NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];

/*/2.在Docments文件夹下拼接一个文件路径

return [doc stringByAppendingPathComponent:@”string.txt”];

}

这里的init代表初始化

例如读取数组就为 [NSArray arrayWithContentsOfFile:arrPath];

//arrPath 为数组存放路径

复杂对象写入文件

什么是复杂对象

1.在Foundation 框架下不存在的数据类

2.无法在程序内通过writeToFile类型的方法写入到文件内

3.复杂对象至少包含一个实例对象

数据持久化方式之一:

归档

:针对于复杂对象 将自定义类的对象转成NSData 再WriteToFile:写入文件

归档的对象必须服从NSCoding协议 实现对应协议的方法

//将mod对象转化为NSData对象

NSMutableData *data = [NSMutableData data];

//1.创建归档工具

NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

//2.归档

[archiver encodeObject:mod forKey:@”ll”];

//3.结束归档

[archiver finishEncoding];

//4.data写入文件
[data writeToFile:[self filePath] atomically:YES];


//反归档

- (IBAction)unAchieve:(id)sender {

//1.获取保存得的data数据

NSData *data = [NSData dataWithContentsOfFile:[self filePath]];

//2.创建反归档工具

NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

//3.反归档

Model *model = [unarchiver decodeObjectForKey:@”ll”];

//4.结束

[unarchiver finishDecoding];

//对数组进行归档

Model *model1 = [[Model alloc] init];

Model *model2 = [[Model alloc] init];

Model *model3 = [[Model alloc] init];

NSArray *arr = @ [model1,model2, model3];

//对数组进行归档时,会对数组中每一个元素进行归档

NSMutableData *data = [NSMutableData data];

//创建归档对象

NSKeyedArchiver *archiever = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

//归档

[archiever encodeObject:arr forKey:@”key”];

//结束归档

[archiever finishEncoding];

//写入文件,进行数据持久化

[data writeToFile:[self filePath] atomically:YES];

//字典进行归档操作时,字典中的复杂对象,也需要服从NSCoding协议,实现协议的方法


文件管理类:NSFileManager

(NSString *)downloadfilepath {

//1.获取Caches文件夹路径

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

//在Caches文件夹下拼接一个文件路径

NSString *downloadpath = [cachesPath stringByAppendingPathComponent:@”download”];

return downloadpath;

}

//判断文件夹是否存在

- (BOOL)isFileExist {

//判断文件夹是否存在
NSFileManager *manager = [NSFileManager defaultManager];
BOOL isExist = [manager fileExistsAtPath:[self downloadfilepath]];
return isExist;


}

//创建文件夹 Caches –> Download

- (IBAction)creatFile:(id)sender {

NSFileManager *manager = [NSFileManager defaultManager];

if (NO == [self isFileExist]) {

//创建

//参数1:指定文件的路径 参数2 如果指定的文件夹没有,则自动创建 参数3:文件夹的属性 参数4:错误信息

BOOL isCreat = [manager createDirectoryAtPath:[self downloadfilepath] withIntermediateDirectories:YES attributes:nil error:nil];

NSLog(@”%@”,isCreat ? @”创建成功”:@”失败”);

}else{ NSLog(@”文件夹存在”);

}

}

//删除

- (IBAction)delectFile:(id)sender {

NSFileManager *manager = [NSFileManager defaultManager];

//如果文件夹存在 ,可删除

if ([self isFileExist]) {

BOOL isMove = [manager removeItemAtPath:[self downloadfilepath] error:nil];

NSLog(@”%@”,isMove ? @”已移除”:@”移除失败”);

}

}

//移动

- (IBAction)removeFile:(id)sender {

NSFileManager *manager = [NSFileManager defaultManager];

//1.移动之前的路径

NSString *sourceFile = [self downloadfilepath];

//移动之后的路径

NSString *destinationPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@”file”];

//3.移动

BOOL ismove = [manager moveItemAtPath:sourceFile toPath:destinationPath error:nil];

NSLog(@”%@”,ismove ?@”yiyidong”:@”移动失败”);

}

//拷贝

- (IBAction)copyFile:(id)sender {

//获取要应用程序包中的资源路径

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@”m1” ofType:@”jpg”];

//获取download的路径

NSString *path = [[self downloadfilepath]stringByAppendingPathComponent:@”nnn.png”];

//拷贝

NSFileManager *manager = [NSFileManager defaultManager];

if ([self isFileExist]) {

BOOL iscopy =[manager copyItemAtPath:imagePath toPath:path error:nil];

NSLog(@”%@”,iscopy ? @”拷贝成功” :@”失败”);

}

}

//文件夹属性

- (IBAction)fileAttributes:(id)sender {

//获取documents文件夹属性路径

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

//2.获取文件夹属性

NSFileManager *manager = [NSFileManager defaultManager];

NSDictionary *dic = [manager attributesOfItemAtPath:docPath error:nil];

//文件夹的大小

NSLog(@”%@”,dic[@”NSFileSize”]);

//文件夹的类型

NSLog(@”%@”,dic[@”NSFileType”]);

//更多文件属性key值, 看 FileAttribute Keys

//文件夹下所有子文件夹路径

NSArray *arr = [manager subpathsAtPath:docPath];

NSLog(@”%ld”,arr.count);

for (NSString *path in arr) {

NSLog(@”%@”, [docPath stringByAppendingPathComponent:path]);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: