IOS数据持久化之归档NSKeyedArchiver, NSUserDefaults,writeToFile

时间:2023-03-08 15:53:45

    //2.文件读写
//支持:NSString, NSArray , NSDictionay, NSData
//注:集合(NSArray, NSDictionay)中得元素也必须是这四种类型, 才能够进行文件读写 //string文件读写
NSString *string = @"假如给我有索纳塔"; //Document
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
//指定文件路径 aaa.txt
NSString *filePath = [docPath stringByAppendingPathComponent:@"aaa.txt"];
NSLog(@"**%@", filePath);
//写入文件
//参数1:文件路径, 如果文件路径下没有此文件, 系统会自动创建一个文件.
//参数2:是否使用辅助文件
//参数3:编码格式
//参数4:错误
NSError *error = nil;
BOOL result = [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
if (result) {
NSLog(@"写入成功");
} else { NSLog(@"写入错误");
}
if (error) {
NSLog(@"出现错误");
} //取值操作,
NSError *error1 = nil;
NSString *contenSring = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error1];
if (error1) {
NSLog(@"error:%@", error1);
} else {
NSLog(@"文件内容%@", contenSring);
}
[contenSring release]; //NSArray的文件读写 NSArray *array = @[@"", @"abc", @"apm"];
//写入操作, 格式XML
//Library, test.txt
//library路径
NSString *libraryPath1 = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
//文件路径
NSString *textPath = [libraryPath1 stringByAppendingPathComponent:@"text.txt"];
NSLog(@"%@", textPath);
//写入
BOOL result4 = [array writeToFile:textPath atomically:YES];
//判断是否写入成功
if (result4) {
NSLog(@"写入成功");
} else {
NSLog(@"写入失败");
} //取值操作 NSArray *bbb = [[NSArray alloc] initWithContentsOfFile:textPath];
NSLog(@"%@", bbb);
[bbb release]; //NSDictionary, 格式:XMl
NSDictionary *dic = @{@"a": @"aaa", @"": @"", @"*" :@"**"};
//Caches, dic.txt
//Caches文件路径
NSString *cachesPath1 = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
//dic.txt路径
NSString *dicPath = [cachesPath1 stringByAppendingPathComponent:@"dic.txt"];
NSLog(@"%@", dicPath);
//写入
BOOL result3 = [dic writeToFile:dicPath atomically:YES];
//判断写入是否成功
if (result3) {
NSLog(@"写入成功");
} else {
NSLog(@"写入shib");
}
//取值操作
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:dicPath];
NSLog(@"%@", dict);
[dict release]; //NSData NSString *tmpPath = NSTemporaryDirectory();
NSString *string2 = @"";
//字符串转data
NSData *data = [string2 dataUsingEncoding:NSUTF8StringEncoding];
//tmp路径
//tmp data.txt
NSString *tmpPath1 = NSTemporaryDirectory();
//data.txt路径
NSString *dataPath = [tmpPath1 stringByAppendingPathComponent:@"data.txt"];
//写入
BOOL result1 = [data writeToFile:dataPath atomically:YES];
//判断是否写入成功
if (result1) {
NSLog(@"写入成功");
} else {
NSLog(@"写入失败");
} //取值
NSData *datat = [[NSData alloc] initWithContentsOfFile:dataPath];
NSString *dataSting = [[NSString alloc] initWithData:datat encoding:NSUTF8StringEncoding];
[datat release];
NSLog(@"%@", dataSting);
[dataSting release];

     //3.归档 / 反归档
//归档的实质:把其他类型数据(比如:Person),先转化成NSData, 再写入文件
//能进行归档的对象, 必须遵守<NSCoding> //归档
Person *person = [[[Person alloc] init] autorelease];
person.name = @"辉哥";
person.age = @"";
person.gender = @"男";
//NSLog(@"%@", person); //可变data
NSMutableData *mData = [[NSMutableData alloc] initWithCapacity:]; //NSKeyedArchiver, 压缩工具, 继承于NSCoder,主要用于编码
NSKeyedArchiver *archiver= [[NSKeyedArchiver alloc] initForWritingWithMutableData:mData];
//把Person对象压到Data中
[archiver encodeObject:person forKey:@"girlFriend"];
//完成压缩
[archiver finishEncoding];
[archiver release];
NSLog(@"%@", mData); //主目录中, person.txt
NSString *homePatha = NSHomeDirectory();
NSString *mDataPath = [homePatha stringByAppendingPathComponent:@"person.txt"];
NSLog(@"%@", mDataPath);
BOOL result = [mData writeToFile:mDataPath atomically:YES];
if (result) {
NSLog(@"写入成功");
} else {
NSLog(@"写入失败");
}
[mData release]; //反归档
NSData *contentData = [[NSData alloc] initWithContentsOfFile:mDataPath];
//NSKeyedUnarchiver解压工具, 继承于NSCoder
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:contentData];
[contentData release];
//通过key找到person
Person *contentPerson = [unarchiver decodeObjectForKey:@"girlFriend"];
NSLog(@"gd%@", contentPerson);
[unarchiver release];
     //数据持久化:数据永久的保存
//数据持久化的实质:把数据写入文件, 再把文件存到硬盘
//IOS沙盒机制:IOS系统为每个app生成一个文件夹(沙盒), 这个文件夹只允许当前的APP访问
//沙盒的主目录
//沙盒主目录的文件夹名字由 十六进制数 和 - 组成, 保证沙盒安全性
//NSHomeDirectory()
NSString *homePath = NSHomeDirectory();
NSLog(@"%@", homePath); //Documents文件
//存放着一些比较重要的用户信息, 比如游戏的存档
//Documents中得文件会被备份 或者 存入iCloud 中, 所以存到documents中得文件不能过大, 如果过大, 会在应用审核过程中遭到拒审
//参数1:文件夹名称
//参数2:搜素域 优先级user>local>network>system
//参数3:相对路径或者绝对路径, yes 是绝对, no是相对
//因为相同文件名的文件可能有多个, 所以返回的是一个数组
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//NSLog(@"%@", paths); NSString *docmentsPath = [paths firstObject];
//NSLog(@"%@", docmentsPath); //Library,资源库 存放一些不太重要, 相对比较大得文件
NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
//NSLog(@"libraryPath:%@", libraryPath);
//Library/Caches, 缓存, 网页缓存, 图片缓存, 应用中得"清理缓存"功能, 就是清理这个文件夹下得内容
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
//NSLog(@"%@", cachesPath);
//LanunchImages, 由LaunchScreen.xib生成的启动图片 //Library/Preferences, 偏好设置, 存放用户对这个应用的设置或配置
//注:路径找不到,通过NSUserDefaults访问 //tmp, 临时文件, 存放下载的压缩包, 解压过后删除
NSString *tmpPath = NSTemporaryDirectory();
NSLog(@"%@", tmpPath); // *.app, 包,用右键,显示包内容, 查看里面存放的文件
//IOS8.0以后, *.app单独存放到一个文件内
// *.app中这个文件,只能够访问,不能够修改(写入)
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSLog(@"***%@", bundlePath); //NSFileManager文件管理工具, 主要用于添加, 移动, 修改, 拷贝文件, 继承于NSObject
//文件管理工具是个单例
NSFileManager *fm = [NSFileManager defaultManager];
//文件路径
NSString *hPath = [[fm URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
NSLog(@"hPath:%@", hPath); //创建文件夹,
//在主目录中创建images文件夹
NSString *mainPath = NSHomeDirectory();
NSString *directoryPath = [mainPath stringByAppendingPathComponent:@"images"];
NSLog(@"%@", directoryPath); NSError *error = nil;
//attributes设置文件夹的属性,读写,隐藏等等
//NSDictionary *attributes = @{NSFileAppendOnly: @YES};
BOOL result = [fm createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:&error];
if (result) {
NSLog(@"创建成功");
} else { NSLog(@"创建失败");
} //创建文件
//在Images文件夹中创建image.png
NSString *imagePath = [directoryPath stringByAppendingPathComponent:@"image.png"];
NSLog(@"%@", imagePath); //找图片
NSString *meinvPath = [[NSBundle mainBundle] pathForResource:@"美女7" ofType:@"png"];
NSData *imageData = [NSData dataWithContentsOfFile:meinvPath]; //创建图片
BOOL result2 = [fm createFileAtPath:imagePath contents:imageData attributes:nil];
if (result2) {
NSLog(@"创建成功");
} else {
NSLog(@"创建失败");
} //判断文件是否存在
if ([fm fileExistsAtPath:imagePath]) {
NSLog(@"存在");
//删除
NSError *error = nil;
BOOL result = [fm removeItemAtPath:imagePath error:&error];
if (result) {
NSLog(@"删除成功");
} else {
NSLog(@"删除失败%@", error);
}
} NSString *path = NSHomeDirectory();
NSString *filePath = [path stringByAppendingPathComponent:@"aaa.txt"];
NSLog(@"1*%@", filePath);
NSString *filePath1 =[path stringByAppendingString:@".aaa.txt"];
NSLog(@"2*%@", filePath1);
NSString *filePath2 = [path stringByAppendingFormat:@"/baa.txt"];
NSLog(@"3*%@", filePath2);
NSString *filePath3 = [path stringByAppendingPathExtension:@"caaa.txt"];
NSLog(@"4*%@", filePath3); //数据持久化的方式
//1. NSUserDefaults, 继承于NSObject, 单例设计模式, 内部存值用的KVC
NSInteger money = ;
money -= ; //存数据, 存放到PreFerences文件夹内的*.plist文件中, 以字典的形式存储
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults setInteger: forKey:@"myMoney"];
//同步操作, 让存入的数据写入文件
[userDefaults synchronize]; //取数据, key和存数据的key保持一致
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
NSInteger myMoney = [user integerForKey:@"myMoney"];
NSLog(@"%ld", myMoney); NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger mmoney = [defaults integerForKey:@"myLifeMoney"];
if (mmoney <= ) {
NSLog(@"不能花了");
} else {
NSLog(@"花了10, 吃了俩");
mmoney -= ;
[defaults setInteger:mmoney forKey:@"myLifeMoney"];
[defaults synchronize];
} //NSUserDefaults, 支持的数据类型:array, dictionary, string, data, date, number, bool
//NSUserDefaults, 一般存一些数值, 不存大量的数据
//是不是第一次启动
NSUserDefaults *userDefault1 = [NSUserDefaults standardUserDefaults];
BOOL isFirst = [userDefault1 boolForKey:@"isFirst"];
if (isFirst == NO) {
NSLog(@"第一次启动");
[userDefault1 setBool:YES forKey:@"isFirst"];
} else {
NSLog(@"不是第一次启动");
}

Person.h 中实现NSCoding协议

#import <Foundation/Foundation.h>

@interface Person : NSObject<NSCoding>

@property (nonatomic , retain) NSString *name, *age, *gender;

@end

Person.m 中实现的方法

 #import "Person.h"

 @implementation Person
- (void)dealloc
{
[_age release];
[_name release];
[_gender release];
[super dealloc]; } - (NSString *)description
{
return [NSString stringWithFormat:@"name:%@, age:%@, gender:%@", _name, _age, _gender];
} #pragma mark - NSCoding
- (void)encodeWithCoder:(NSCoder *)aCoder {
//编码
[aCoder encodeObject:self.name forKey:@"NAME"];
[aCoder encodeObject:self.age forKey:@"AGE"];
[aCoder encodeObject:self.gender forKey:@"GENDER"];
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
//解码
self.name = [aDecoder decodeObjectForKey:@"NAME"];
self.age = [aDecoder decodeObjectForKey:@"AGE"];
self.gender = [aDecoder decodeObjectForKey:@"GENDER"];
}
return self;
} @end

@interface Person : NSObject<NSCoding>