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应用程序只能在为该改程序创建的文件系统中读取文件,不可以去其它地方访问,此区域被成为沙盒,所以所有的非代码文件都要保存在此,例如图像,图标,声音,映像,属性列表,文 ...
 
随机推荐
- 点滴积累【JS】---JS小功能(onmousedown实现鼠标拖拽div移动)
			
效果: 思路: 利用onmousedown事件实现拖拽.首先获得鼠标横坐标点和纵坐标点到div的距离,然后当鼠标移动后再用可视区的距离减去横纵坐标与div的距离.然后在判断不让DIV移出可视区,然后再 ...
 - atitit.session的原理以及设计 java php实现的异同
			
atitit.session的原理以及设计 java php实现的异同 1. session的保存:java在内存中,php脚本因为不能常驻内存,所以在文件中 1 2. php的session机制 1 ...
 - ado连接sql server
			
//ado连接sql server //头文件加上以下这句. #import "C:\Windows\system\msado15.dll" no_namespace rename ...
 - python学习之count()
			
定义: count()方法用于统计对象中,某个字符出现的次数 语法: str.count(sub, start= ,end=len(string)) sub:搜索的对象 start和end:搜索的范围 ...
 - VMware12环境下安装CentOS7的vmware-tools
			
一.最小化安装 1.进入系统之后,要配置network网络. 首先ping www.baidu.com (Ctrl+z 推出正在执行的命令) 如果ping不通,则修改: vi /etc/ ...
 - protobuf java学习
			
本文档为java编程人员使用protocol buffer提供了一个基本的介绍,通过一个简单的例程进行介绍.通过本文,你可以了解到如下信息: 1.在一个.proto文件中定义一个信息格式. 2.使用p ...
 - Jquery学习笔记(8)--京东导航菜单(2)增加弹框
			
京东导航,添加中间的弹框栏,使用position定位,放在左侧栏的li标签里面,成为一个整体,保证鼠标在弹框里的时候,弹框不消失: <!DOCTYPE html> <html lan ...
 - 排查PHP-FPM占用CPU过高
			
发现 如何发现的呢?当然是使用top命令,发现系统的load average>3,这说明系统已经处于比较高的负载中. 尝试解决 当我把php-fpm重启后,没过一会儿又开始cpu狂飙!这是什么鬼 ...
 - jquery怎么实现页面刷新后保留鼠标点击addclass的样式
			
$(document).ready(function(){ $('#rating li').each(function(){ if($($(this)).attr('id')==String(wind ...
 - Could not resolve dependencies for project
			
最近项目上使用的是idea ide的多模块话,需要模块之间的依赖,比如说系统管理模块依赖授权模块进行认证和授权,而认证授权模块需要依赖系统管理模块进行,然后,我就开始相互依赖,然后出现这样的问题: “ ...