数据持久化以及沙盒路径

什么是沙盒机制

简单对象写入文件
NSFileManager
复杂对象写入文件
 
数据持久化
什么是数据持久化?
数据的永久存储
为什么要做数据持久化?:存储在内存中的数据,程序关闭,内存释放,数据丢失,这种数据是临时的,用户下次打开应用程序,还要重新联网去刷新数据,无疑增加了用户的负担
数据持久化的本质:数据保存成文件,存储到程序的沙盒中
 
什么是沙盒机制?
每个应用程序位于文件系统的严格限制部分
每个应用程序只能在为该程序创建的文件系统中读取文件
每个应用程序在iOS系统内部都放在了统一的文件夹目录下面
沙盒的本质就是一个文件夹,名字是随机分配的
 
沙盒路径的位置
1.通过Finder查找程序的沙盒相对路径
~/Library/Application Support/iPhone Simulator
 
常见问题
模拟器路径内有可能包含多个系统版本的路径
 
沙盒机制
通过代码查找程序沙盒相对路径
NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory directory, NSSearchPathDomainMask domainMask domainMask, BOOL expandTilde)
 
获取沙盒目录路径的方法
NSHomeDirectory----------------------->沙盒主路径
NSDocumentDirectory------------------>Documents文件夹
NSLibraryDirectory---------------------->Library文件夹
NSCachesDirectory---------------------->Caches文件夹
NSTemporaryDirectory()---------------->tmp文件夹
 
NSBundle
每个应用程序文件夹内的app文件是什么?
每个应用程序文件夹内的app文件路径如何获取?
 
获取应用程序app文件夹内的文件路径
获取应用程序的相关配置属性
 
二、简单对象写入文件

// 字符串对象写入文件

    // 获取沙盒目录

    NSString *documentsPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES).lastObject;

    NSLog(@"%@", documentsPath);

    // 方法二

    NSString *homePath = NSHomeDirectory();

    // homePath = [homePath stringByAppendingString:@"/Documents"];

    homePath = [homePathstringByAppendingPathComponent:@"Documents"];

    NSLog(@"%@", homePath);

    

    // 2.拼接文件路径

    NSString *filePath = [documentsPathstringByAppendingPathComponent:@"abc.txt"];

    NSLog(@"%@", filePath);

    

    NSString *str = @"情人节了,赛赛你还是一个人吗?";

    // 将str中的字符串写入文件

     [str writeToFile:filePath atomically:YES encoding:NSUTF8StringEncodingerror:nil];

    // 上面三行已经实现了把数据存入abc.txt文件夹下,实现数据持久化

    NSString *str2 = [NSString stringWithContentsOfFile:filePathencoding:NSUTF8StringEncoding error:nil];

    NSLog(@"%@", str2);

    

    // 数组对象写入文件

    // 在文件夹后面拼接数组txt文件,实现数组的添加

    NSString *arrayFilePath = [documentsPathstringByAppendingPathComponent:@"array.txt"];

    NSArray *array = @[@"大赛赛", @"大鼠标", @"小超超", @"小彪彪", @"大黄黄",@"大波波"];

    [array writeToFile:arrayFilePath atomically:YES];

    

    NSArray *array2 = [NSArray arrayWithContentsOfFile:arrayFilePath];

    NSLog(@"%@", array2);

    

    

    // 字典对象写入文件

    // 在文件夹后面拼接字典txt文件,实现字典的添加

    NSString *dictionaryFilePath = [documentsPathstringByAppendingPathComponent:@"dictionary.txt"];

    NSDictionary *dictionary = @{@"saisai": @"赛赛",

                                 @"chaochao":@"超超",

                                 @"doudou":@"豆豆"};

    [dictionary writeToFile:dictionaryFilePath atomically:YES];

    

    NSDictionary *dictionary2 = [NSDictionarydictionaryWithContentsOfFile:dictionaryFilePath];

    NSLog(@"%@", dictionary2);

    

    // 图片对象写入文件

    // 将图片资源转为NSData类型,再储存

     UIImage *image = [UIImage imageNamed:@"1.png"];

    // 将图片转化为NSData

    NSData *imageData = UIImagePNGRepresentation(image);

    

    // 拼接data数据路径

    NSString *dataFilePath = [documentsPathstringByAppendingPathComponent:@"image.txt"];

    // 将data数据写入文件中

    [imageData writeToFile:dataFilePath atomically:YES];

三、NSFileManager

NSFileManager, 文件管理,使用detaultManager, 创建单例对象。

可以创建文件夹

可以创建、移动、复制、删除文件

可以判断文件是否存在

//NSFileManager

    NSString *path1 = [documentsPathstringByAppendingPathComponent:@"path1/path2/path3"];

    NSLog(@"%@", path1);

    

    // 创建文件夹

    [[NSFileManager defaultManager] createDirectoryAtPath:path1withIntermediateDirectories:YES attributes:nil error:nil];

    

    // 判断文件是否存在

    BOOL b = [[NSFileManager defaultManager]fileExistsAtPath:dictionaryFilePath];

    NSLog(@"%d", b);

四、复杂对象写入文件

#import 

// 首先创建一个Person类,遵守NSCoding协议,在.m文件中实现编码和反编码的方法

@interface Person : NSObject<</span>NSCoding>

@property (nonatomic, copy) NSString *name;

@property (nonatomic, copy) NSString *gender;

@property (nonatomic, assign) NSInteger age;

@end

.m文件

#import "Person.h"

#define kName @"name"

#define kGender @"gender"

#define kAge @"age"

@implementation Person

#pragma mark 进行编码

- (void)encodeWithCoder:(NSCoder *)aCoder

{

    [aCoder encodeObject:self.name forKey:kName];

    [aCoder encodeObject:self.gender forKey:kGender];

    // 几个属性就要写几行,对于NSInteger类型的有专用的方法

    [aCoder encodeInteger:self.age forKey:kAge];

}

#pragma mark 反编码

- (id)initWithCoder:(NSCoder *)aDecoder

{

    self = [super init];

    if (self) {

        self.name = [aDecoder decodeObjectForKey:kName];

        self.gender = [aDecoder decodeObjectForKey:kGender];

        self.age = [aDecoder decodeIntegerForKey:kAge];

    }

    return self;

}

#pragma mark dealloc

- (void)dealloc

{

    [_name release], _name = nil ;// 安全释放

    [_gender release], _gender = nil; // 安全释放

    [super dealloc];

}

@end

在主控制器中引入Person类对象

#import "JYFViewController.h"

#import "Person.h"

 
下面即是方法

// 创建Person对象

    Person *person = [[Person alloc] init];

    person.name = @"彪彪";

    person.gender = @"男";

    person.age = 22;

// 创建可变的NSMutableData准备存放person对象

    NSMutableData *personData = [NSMutableData data];

// 创建归档工具

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

 

// 进行二进制的转换

    [archiver encodeObject:person forKey:@"personKey"];

 

// 完成转换

    [archiver finishEncoding];

// 创建路径

    NSString *personFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES).lastObjectstringByAppendingPathComponent:@"person.abc"];

// 进行NSData对象的写入

    //[personData writeToFile:personFilePath atomically:YES];

 

// 反归档

    // 1.创建一个data用来接受person文件路径中的数据

    NSData *data = [NSData dataWithContentsOfFile:personFilePath];

// 2.使用data去创建反归档工具

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

 

// 3.使用工具把二进制数据转回复杂对象

    Person *p = [unarchiver decodeObjectForKey:@"personKey"];

 // 4.结束反归档

    [unarchiver finishDecoding];

// 简便方法

    // 创建路径

    NSString *chaochoaFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES).lastObjectstringByAppendingPathComponent:@"chaochao.avi"];

    NSLog(@"%@", chaochoaFilePath);

    

    // 创建对象

    Person *chaochao = [[Person alloc] init];

    chaochao.name = @"超超";

    chaochao.gender = @"男";

    chaochao.age = 23;

    

    // 进行数据保存

    [NSKeyedArchiver archiveRootObject:chaochao toFile:chaochoaFilePath];

    

    // 读取

    Person *chaochaoPerson = [NSKeyedUnarchiverunarchiveObjectWithFile:chaochoaFilePath];

    NSLog(@"%@ %@ %d", chaochaoPerson.name, chaochaoPerson.gender, chaochao.age);

总结:

沙盒机制

简单对象写入文件,只能是NSString、NSArray、NSDictionary、NSData

复杂对象写入文件,遵守NSCoding协议,实现代理方法

原文地址:https://www.cnblogs.com/vajra1025/p/4711560.html