//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. Django Ajax提交数据请求

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  2. JSP应用开发 -------- 电纸书(未完待续)

    http://www.educity.cn/jiaocheng/j9415.html JSP程序员常用的技术   第1章 JSP及其相关技术导航 [本章专家知识导学] JSP是一种编程语言,也是一种动 ...

  3. Atitit.eclipse git使用

    Atitit.eclipse git使用 1. Git vs svn1 1.1. 直接记录快照,而非差异比较1 1.2. Git的patch则不依附于branch,commit和commit之间的关系 ...

  4. Atitit.执行cmd 命令行 php

    Atitit.执行cmd 命令行 php 1. 执行cmd 命令行,调用系统命令的基础 1 1.1. 实际执行模式 1 1.2. 空格的问题 1 1.3. 中文路径的问题,程序文件读取编码设置 1 1 ...

  5. FPGA开发流程1(详述每一环节的物理含义和实现目标)

    要知道,要把一件事情做好,不管是做哪们技术还是办什么手续,明白这个事情的流程非常关键,它决定了这件事情的顺利进行与否.同样,我们学习FPGA开发数字系统这个技术,先撇开使用这个技术的基础编程语言的具体 ...

  6. ruby之各种概念

    一.引言 刚开始接触ruby,遇到问题于是上网查资料,但是有时候却又看不懂,这很大一部分原因是我不知道一些关于ruby的概念名词是什么意思,所以看了别人的回答也理解不了. 二.各种名词 ruby:这个 ...

  7. modbus学习

  8. Java动态代理原理及其简单应用

    概念 代理对象和被代理对象一般实现相同的接口,调用者与代理对象进行交互.代理的存在对于调用者来说是透明的,调用者看到的只是接口.代理对象则可以封装一些内部的处理逻辑,如访问控制.远程通信.日志.缓存等 ...

  9. 二维码生成库phpqrcode使用小结

    <img src="data:image/png;base64,这里是base64编码内容" /> 只需要里边的phpqrcode.php这一个文件就可以生成二维码了 ...

  10. org.springframework.beans.factory.parsing.BeanDefinitionParsingException

    今天在练习spring aop时.调试程序出现下面错误 org.springframework.beans.factory.parsing.BeanDefinitionParsingException ...