初级数据持久化 - 沙盒机制 归档 与反归档
通过代码查找程序沙盒相对路径
NSDocuments文件夹路径
NSArray *documentsPathArry NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *document = [documentsPathArry lastObject];
NSLog(@"%@", document);
// NSCaches 缓存文件夹路径
NSArray *cachesPatharray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachespath = cachesPatharray[0];
NSLog(@"%@", cachespath);
// 打印temp文件夹 NSTemporaryDirectory()
// 该文件夹一般存储 临时文件夹
NSString *tempPath = NSTemporaryDirectory();
NSLog(@"%@", tempPath);
// 打印沙盒主目录路径 NSHomeDirectory()
NSString *homePath = NSHomeDirectory();
NSLog(@"%@", homePath);
// 简单对象写入文件
// 注意 :如果你写入字典或者数组 那么数组字典中存储的数据必须是简单对象 无法写入复杂对象
- (void)writeFile
{
// 简单对象
// 字符串 字典 数组 data...系统写好的类
// 写入文件的路径
// 写入documents 路径下写入xiaoshuo.text
NSArray *documentsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *document = documentsArray[0];
NSString *path = [document stringByAppendingString:@"/xiaoshuo.text"];
NSString *str = @"第一章 在一个月黑风高的早上";
// atomically 如果yes 在你写入的过程中出现程序崩溃 不影响写入
[str writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@", path);
// 简单拼接对象写入步骤
// 1.拼接要写入的路径 (注意的路径一定要拼接对)
// 2. 调用写方法完事
// 写入一个数组 shuzu.plist
// 必须给后缀类型 你不给呢 就默认是text格式
NSString *arrPath = [document stringByAppendingPathComponent:@"shuzu.plist"];
NSArray *array = @[@"永乐", @"永飞", @"哈哈"];
// 调用写入方法
[array writeToFile:arrPath atomically:YES];
NSLog(@"%@", arrPath);
// 写入一个字典 zidian.plist
NSString *dicPath = [document stringByAppendingPathComponent:@"zidian.plist"];
NSDictionary *dic = @{@"name": @"xiaofang"};
[dic writeToFile:dicPath atomically:YES];
NSLog(@"%@", dicPath);
// data的写入 后缀.da
NSString *dataPath = [document stringByAppendingPathComponent:@"data.da"];
NSString *dataStr = @"你猜我是谁";
NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
// 写入文件
[data writeToFile:dataPath atomically:YES];
NSLog(@"%@", dataPath);
// 复杂对象
// 自定义的类 比如person
}
// 读取写入的文件
- (void)readingFile
{
// 读字符串
// 获取路径
NSArray *documentsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *document = documentsArray[0];
NSString *path = [document stringByAppendingString:@"/xiaoshuo.text"];
// 从路径中读取字符串
NSString *str = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@", str);
// 读取数组的文件
NSString *arrPath = [document stringByAppendingPathComponent:@"shuzu.plist"];
// 获取路径
NSArray *array = [NSArray arrayWithContentsOfFile:arrPath];
NSLog(@"%@", array);
// 读取字典
// 获取路径
NSString *dicPath = [document stringByAppendingPathComponent:@"zidian.plist"];
NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:dicPath];
NSLog(@"%@", dic);
// 读取data
NSString *dataPath = [document stringByAppendingPathComponent:@"data.da"];
NSData *data = [NSData dataWithContentsOfFile:dataPath];
// 将data转化为字符串
NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", dataStr);
}复杂对象写入文件 1.初始化对象 2. 创建一个归档对象3 进行归档编码 4 编码完成5 把存有复杂对象的文件data 写入文件中 进行持久化(1 搞路径2 调用写入方法)6 释放归档对象
复杂对象进行持久化 需要遵守一个协议<NSCoding>
@interface JJModel : NSObject<NSCoding>
@property (nonatomic, retain) NSString *name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, retain) NSData *data;
@end
在.m中
@implementation JJModel
- (void)dealloc
{
[_name release];
[_data release];
[super dealloc];
}
// 对复杂对象进行持久化 叫做归档与反归档 (编码与解码)
// 归档方法 编码成可以持久化的格式
- (void)encodeWithCoder:(NSCoder *)aCoder
{
// 对每一个属性 都要进行重新编码
// 注意: 属性的类型
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
[aCoder encodeObject:self.data forKey:@"data"];
}
// 反归档方法 解码的过程
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {
// 解码的过程
// 跟编码一样 除了对象类型以外 也是有特殊解码方法
// 注意:编码的时候 你给的KEY 要和解码key一样
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
self.data = [aDecoder decodeObjectForKey:@"data"];
}
return self;
}
@end
创建一个rootcontroller 设置成主控制器
#import "RootViewController.h"
#import "JJModel.h"
#define kDocumentPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]
#define kCachesPath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]
@interface RootViewController ()
@end
@implementation RootViewController
- (void)viewDidLoad {
[super viewDidLoad];
//Do any additional setup after loading the view.
[self createFile];
[self moveFile];
[self copyFile];
[self deleteFile];
[self isExistFile];
[self archiver];
[self unArchiver];
}
// 创建一个文件夹
- (void)createFile
{
// 需求 在documents下创建一个Download文件夹
NSArray *documentsArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *doucumentPath = documentsArr[0];
// 拼接路径
NSString *downloadPath = [doucumentPath stringByAppendingPathComponent:@"Download"];
NSLog(@"%@", downloadPath);
// 创建文件夹
// 文件管理者 这个类 是个单例类 用来对文件夹进行操作
NSFileManager *manager = [NSFileManager defaultManager];
// withIntermediateDirectories
// 如果yes情况下 要创建的文件 存在的话 可以对其覆盖
// 反之 文件存在的话 不能对其覆盖 (创建失败)
BOOL isCreatFile = [manager createDirectoryAtPath:downloadPath withIntermediateDirectories:YES attributes:nil error:nil];
NSLog(@"%d", isCreatFile);
}
// 移动文件夹
- (void)moveFile
{
// 获取原来的路径
NSString *oldPath = [kDocumentPath stringByAppendingPathComponent:@"Download"];
// 获取新路径 libray 下的Caches 文件夹
NSString *newPath = [kCachesPath stringByAppendingPathComponent:@"Download"];
// 创建 文件管理者类的对象(单例对象)
NSFileManager *manager = [NSFileManager defaultManager];
// 移动文件夹
BOOL isMoved = [manager moveItemAtPath:oldPath toPath:newPath error:nil];
NSLog(@"%d", isMoved);
}
// 复制文件夹
- (void)copyFile
{
// libaray 下的Caches 文件夹 download 复制到document文件夹下
NSString *oldPath = [kCachesPath stringByAppendingPathComponent:@"download"];
NSString *newPath = [kDocumentPath stringByAppendingPathComponent:@"downLoad"];
// 创建文件管理对象
NSFileManager *manager = [NSFileManager defaultManager];
// 复制
BOOL isCopy = [manager copyItemAtPath:oldPath toPath:newPath error:nil];
NSLog(@"%d", isCopy);
}
// 删除文件夹
- (void)deleteFile
{
// 获取要删除的路径
NSString *deletePath = [kDocumentPath stringByAppendingPathComponent:@"Download"];
// 创建文件管理对象
NSFileManager *manager = [NSFileManager defaultManager];
BOOL isDelete = [manager removeItemAtPath:deletePath error:nil];
NSLog(@"%d", isDelete);
}
// 判断文件夹是否存在
- (void)isExistFile
{
// 获取 要判断的路径
NSString *path = [kCachesPath stringByAppendingPathComponent:@"download"];
// 创建文件管理对象
NSFileManager *manager = [NSFileManager defaultManager];
BOOL isExist = [manager isExecutableFileAtPath:path];
NSLog(@"%d", isExist);
}
// 复杂对象归档
- (void)archiver
{
// 初始化对象
JJModel *model = [[JJModel alloc] init];
// 赋值对象
model.name = @"MJJ";
model.age = 49;
// 图片
// 把一个png格式转化成data
model.data = UIImagePNGRepresentation([UIImage imageNamed:@"IMG_1873"]);
NSMutableData *data = [NSMutableData data];
// 创建一个归档对象
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
// 进行归档编码
[archiver encodeObject:model forKey:@"JJModel"];
// 编码完成
[archiver finishEncoding];
// 实际上归档 相当于把编码完的对象保存data中
// NSLog(@"---------%@", data);
// 把存有复杂对象的文件data 写入文件中 进行持久化
// 搞路径
NSString *dataPath = [kDocumentPath stringByAppendingPathComponent:@"JJmodel.da"];
// NSLog(@"=======%@", dataPath);
// 调入写入方法
[data writeToFile:dataPath atomically:YES];
// 释放归档对象
[archiver release];
}
// 反归档 (解码的过程)
- (void)unArchiver
{
// 搞路径
NSString *path = [kDocumentPath stringByAppendingPathComponent:@"JJModel.da"];
// 获取刚才归档的data
NSData *data = [NSData dataWithContentsOfFile:path];
// 创建 反归档对象
NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
// 解码 返回一个对象 应该是JJModel
// 这个key 一定要和刚才归档的时候的key一致
JJModel *model = [unArchiver decodeObjectForKey:@"JJModel"];
// 反归档完成
[unArchiver finishDecoding];
// 释放反归档对象
[unArchiver release];
NSLog(@"%@", model);
UIImage *image = [UIImage imageWithData:model.data];
}