ios专题 -归档保存数据
2024-10-16 19:54:20
关键类:NSKeyedArchiver 与 NSKeyedUnarchiver
采用归档的形式来保存数据,该数据对象需要遵守NSCoding协议,并且该对象对应的类必须提供encodeWithCoder:和initWithCoder:方法。前一个方法告诉系统怎么对对象进行编码,而后一个方法则是告诉系统怎么对对象进行解码
例子:
LQAnimal.h
#import <UIKit/UIKit.h> @interface LQAnimal : NSObject <NSCoding> @property (strong) NSString *animalType; @end
LQAnimal.m
#import "LQAnimal.h" @implementation LQAnimal @synthesize animalType = _animalType; /*
*从未归档数据中,初始化对象
*/
- (id) initWithCoder:(NSCoder *) theCoder
{
LQAnimal *what = [[LQAnimal alloc] init]; what.animalType = [theCoder decodeObjectForKey:@"type"]; return what;
} /*
*归档时,编码
*/
- (void) encodeWithCoder:(NSCoder *)theCoder
{
[theCoder encodeObject:self.animalType forKey:@"type"];
} @end
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[];
NSString *detailPath = [NSString stringWithFormat:@"%@/animal.txt",path];
LQAnimal *animal = [[LQAnimal alloc] init];
//animal.animalType = @" little fat sheep ";
animal.animalType = @" big fat sheep ";
BOOL isOK = [NSKeyedArchiver archiveRootObject:animal toFile:detailPath];
if (isOK) {
NSLog(@"save object success!");
LQAnimal *getAnimal = [NSKeyedUnarchiver unarchiveObjectWithFile:detailPath];
NSLog(@"APP get animal type:%@", getAnimal.animalType);
} else{
NSLog(@"save object fail!");
}
执行结果:
2014-01-03 19:12:22.144 Objc[696:c07] save object success!
2014-01-03 19:12:25.601 Objc[696:c07] APP get animal type: big fat sheep
我执行后,也检查过了animal.txt文本内容,发现系乱码。。
bplist00‘T$topX$objectsX$versionY$archiver—Trootħ
U$null“
V$classTtypeÄÄ_ big fat sheep “X$classesZ$classname¢XLQAnimalXNSObjectXLQAnimal܆_NSKeyedArchiver(:<AGLSXZ\ns|áäìú•™º
这种模式只适合少量配置数据的存储。优点就系够简单。起码比sqlite简单很多。
最新文章
- iOS - 静态库的创建与使用
- Deadlock Detecting--转
- IE里面的一些BUG记录
- iOS Library not loaded: Reason: image not found
- MVVM架构~前台后台分离的思想与实践
- 2015baidu复赛2 连接的管道(mst &;&; 优先队列prim)
- Android系统自带样式(@android:style/) (转)
- Shell的概念
- ***ECharts图表入门和最佳实践
- http://nxlhero.blog.51cto.com/962631/1666250?plg_nld=1&;plg_uin=1&;plg_auth=1&;plg_nld=1&;plg_usr=1&;plg_vkey=1&;plg_dev=1
- 批量将MP4 转换为 MP3
- IO 流—>;>;>;补充
- ios页面跳转
- ssh相关命令
- Linux中Nginx反向代理下的tomcat集群
- 前端构建之gulp与常用插件(转载)
- 使用HttpClient进行https连接(一)
- spring学习(二) ———— AOP之AspectJ框架的使用
- css制作表格
- 用Jquery获取checkbox多个选项