IOS数据持久化之归档NSKeyedArchiver, NSUserDefaults,writeToFile
//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>
IOS数据持久化之归档NSKeyedArchiver, NSUserDefaults,writeToFile的更多相关文章
- iOS开发笔记-swift实现iOS数据持久化之归档NSKeyedArchiver
IOS数据持久化的方式分为三种: 属性列表 (plist.NSUserDefaults) 归档 (NSKeyedArchiver) 数据库 (SQLite.Core Data.第三方类库等 归档(又名 ...
- IOS数据持久化之归档NSKeyedArchiver
IOS数据持久化的方式分为三种: 属性列表 (自定义的Property List .NSUserDefaults) 归档 (NSKeyedArchiver) 数据库 (SQLite.Core Data ...
- iOS数据持久化存储:归档
在平时的iOS开发中,我们经常用到的数据持久化存储方式大概主要有:NSUserDefaults(plist),文件,数据库,归档..前三种比较经常用到,第四种归档我个人感觉用的还是比较少的,恰恰因为用 ...
- iOS 数据持久化(扩展知识:模糊背景效果和密码保护功能)
本篇随笔除了介绍 iOS 数据持久化知识之外,还贯穿了以下内容: (1)自定义 TableView,结合 block 从 ViewController 中分离出 View,轻 ViewControll ...
- iOS -数据持久化方式-以真实项目讲解
前面已经讲解了SQLite,FMDB以及CoreData的基本操作和代码讲解(CoreData也在不断学习中,上篇博客也会不断更新中).本篇我们将讲述在实际开发中,所使用的iOS数据持久化的方式以及怎 ...
- iOS数据持久化方式及class_copyIvarList与class_copyPropertyList的区别
iOS数据持久化方式:plist文件(属性列表)preference(偏好设置)NSKeyedArchiver(归档)SQLite3CoreData沙盒:iOS程序默认情况下只能访问自己的程序目录,这 ...
- iOS 数据持久化(1):属性列表与对象归档
@import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css); @import url(/ ...
- iOS 之持久化存储 plist、NSUserDefaults、NSKeyedArchiver、数据库
1.什么是持久化? 本人找了好多文章都没有找到满意的答案,最后是从孙卫琴写的<精通Hibernate:Java对象持久化技术详解>中,看到如下的解释,感觉还是比较完整的.摘抄如下: 狭义的 ...
- iOS数据持久化-OC
沙盒详解 1.IOS沙盒机制 IOS应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒,所以所有的非代码文件都要保存在此,例如图像,图标,声音,映像,属性列表,文 ...
随机推荐
- Atitit.减少http请求数方案
Atitit.减少http请求数方案 1. 原理与方法1 1.1. -------jsp1 1.2. "index/js.txt";2 1.3. connReduceDync2 1 ...
- Apollo配置中心转
尊重原创,本文转自:https://www.cnblogs.com/FlyAway2013/p/8811385.html 前我们项目,所有的配置基本都是通过本地properties 文件进行配置的,比 ...
- MySQL主从同步那点事儿
一.前言 关于mysql主从同步,相信大家都不陌生,随着系统应用访问量逐渐增大,单台数据库读写访问压力也随之增大,当读写访问达到一定瓶颈时,将数据库的读写效率骤然下降,甚至不可用;为了解决此类问题,通 ...
- iptables详细教程:基础、架构、清空规则、追加规则、应用实例(转)
iptables防火墙可以用于创建过滤(filter)与NAT规则.所有Linux发行版都能使用iptables,因此理解如何配置iptables将会帮助你更有效地管理Linux防火墙.如果你是第一次 ...
- Cookie的新增,设置与清除
addCookieBtn.addEventListener('click',function () { document.cookie='imooc=www.imooc.com;expires=201 ...
- Redis-ha(sentinel)
redis的sendtinel 是用来管理多个redis服务器的 作用 • 监控:监控主从服务器是否运作正常(通过给服务器发送心跳包的方式) • 提醒:当某个Redis服务器出现异常时,可以通过 ...
- windows共享文件的方法
众所周知,一个宿舍,一个公司处在一个局域网络中,在不能使用外网通信情况下,此时,我们忘带U盘或者硬盘,同学或同事之间需要拷贝资料或者数据,是不是就不能实现了呢?答案是否定的.微软为了解决这种不必要的麻 ...
- Effective Java学习笔记--创建和销毁对象
创建和销毁对象 一.静态工厂方法代替构造器 静态工厂方法的优缺点 优点: 1.可以自定义名称(可以将功能表述的更加清晰) 2.不必每次调用都创建新的对象(同一对象重复使用) 3.返回的类型可以是原返回 ...
- Activiti(一)--安装配置具体解释
有一段时间没有更新文章了,尽管有一直在写文章,但是一直没有更新到博客内,这段时间写的文章大多还是以技术为主. 接下来的系列文章将会来讨论企业工作流的开发,主要是来研究开源工作流Activiti的使用. ...
- Mongodb 和 Solr 实时同步
一.安装前准备 1.mongo-connector(基于python)中间件 2.python-3.4.3.msi 3.Mongodb 4.Solr 二.配置Mongodb集群 1).配置replic ...