//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的更多相关文章

  1. iOS开发笔记-swift实现iOS数据持久化之归档NSKeyedArchiver

    IOS数据持久化的方式分为三种: 属性列表 (plist.NSUserDefaults) 归档 (NSKeyedArchiver) 数据库 (SQLite.Core Data.第三方类库等 归档(又名 ...

  2. IOS数据持久化之归档NSKeyedArchiver

    IOS数据持久化的方式分为三种: 属性列表 (自定义的Property List .NSUserDefaults) 归档 (NSKeyedArchiver) 数据库 (SQLite.Core Data ...

  3. iOS数据持久化存储:归档

    在平时的iOS开发中,我们经常用到的数据持久化存储方式大概主要有:NSUserDefaults(plist),文件,数据库,归档..前三种比较经常用到,第四种归档我个人感觉用的还是比较少的,恰恰因为用 ...

  4. iOS 数据持久化(扩展知识:模糊背景效果和密码保护功能)

    本篇随笔除了介绍 iOS 数据持久化知识之外,还贯穿了以下内容: (1)自定义 TableView,结合 block 从 ViewController 中分离出 View,轻 ViewControll ...

  5. iOS -数据持久化方式-以真实项目讲解

    前面已经讲解了SQLite,FMDB以及CoreData的基本操作和代码讲解(CoreData也在不断学习中,上篇博客也会不断更新中).本篇我们将讲述在实际开发中,所使用的iOS数据持久化的方式以及怎 ...

  6. iOS数据持久化方式及class_copyIvarList与class_copyPropertyList的区别

    iOS数据持久化方式:plist文件(属性列表)preference(偏好设置)NSKeyedArchiver(归档)SQLite3CoreData沙盒:iOS程序默认情况下只能访问自己的程序目录,这 ...

  7. iOS 数据持久化(1):属性列表与对象归档

    @import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css); @import url(/ ...

  8. iOS 之持久化存储 plist、NSUserDefaults、NSKeyedArchiver、数据库

    1.什么是持久化? 本人找了好多文章都没有找到满意的答案,最后是从孙卫琴写的<精通Hibernate:Java对象持久化技术详解>中,看到如下的解释,感觉还是比较完整的.摘抄如下: 狭义的 ...

  9. iOS数据持久化-OC

    沙盒详解 1.IOS沙盒机制 IOS应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒,所以所有的非代码文件都要保存在此,例如图像,图标,声音,映像,属性列表,文 ...

随机推荐

  1. 为select的option绑定键盘事件

    1. 目的 可以使用快捷键1.2.3.4等自动选中select框对应的option 2. 代码 <select id="selectItem" class="for ...

  2. Atitit.  Exception in thread "main" java.lang.Error: Unresolved compilation problem:

    Atitit.  Exception in thread "main" java.lang.Error: Unresolved compilation problem: 1.1. ...

  3. Atitit.index manager api design 索引管理api设计

    Atitit.index manager api design 索引管理api设计 1. kw1 1.1. 索引类型 unique,normal,fulltxt1 1.2. 聚集索引(clustere ...

  4. Secure Spring REST API using Basic Authentication

    What is Basic Authentication? Traditional authentication approaches like login pages or session iden ...

  5. 544. Top k Largest Numbers【medium】

    Given an integer array, find the top k largest numbers in it.   Example Given [3,10,1000,-99,4,100] ...

  6. 5.14日学习内容1:jquery表单相关知识

    <script> $comment.animate({height:'+=50'},400);//在原来的基础上加50: $('.smaller').click(function(){ i ...

  7. linux学习笔记8--命令touch

    linux的touch命令不常用,一般在使用make的时候可能会用到,用来修改文件时间戳,或者新建一个不存在的文件. touch命令有两个功能:一是用于把已存在文件的时间标签更新为系统当前的时间(默认 ...

  8. Extjs的完成按钮和位置

    this.toolbar.add('->') ---重点是这个箭头,他是控制位置的 this.CompleteDataAction = new Ext.Action({ text : '完成', ...

  9. redis-trib构建集群

    https://blog.csdn.net/qq_35946990/article/details/78957618

  10. Easyui data方法扩展finder

    finder: function(jq, conditions){ if(!$(jq).data("OriginalData")){ $(jq).data("Origin ...