归档存储
来源:互联网 发布:网络面板接线图解 a b 编辑:程序博客网 时间:2024/05/13 00:12
归档注意存储对象一定要遵守NSCoding协议实现其归档和解档方法,对其需要存储对象的属性进行归档和解档.
新建需要存储的对象
Person.h
//// Person.h// 归档和解档//// Created by gaocai on 16/7/18.// Copyright © 2016年 gaocai. All rights reserved.//#import <Foundation/Foundation.h>@interface Person : NSObject<NSCoding>@property (nonatomic, assign) int age;@property (nonatomic, strong) NSString *name;@end
Person.m
//// Person.m// 归档和解档//// Created by gaocai on 16/7/18.// Copyright © 2016年 gaocai. All rights reserved.//#import "Person.h"@implementation Person//归档存储- (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:@"张三" forKey:@"name"]; [aCoder encodeInt:24 forKey:@"age"];}//解档读取- (instancetype)initWithCoder:(NSCoder *)aDecoder { if (self == [super init]) { _name = [aDecoder decodeObjectForKey:@"name"]; _age = [aDecoder decodeIntForKey:@"age"]; } return self;}@end
ViewController.m
//// ViewController.m// 归档和解档//// Created by gaocai on 16/7/18.// Copyright © 2016年 gaocai. All rights reserved.//#import "ViewController.h"#import "Person.h"@interface ViewController ()@end@implementation ViewController//存- (IBAction)save:(id)sender { //获得缓存文件路径 NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]; //拼接文件存储全路径 NSString *pathFile = [cachePath stringByAppendingPathComponent:@"data.txt"]; //需要归档的对象(存储) Person *p = [[Person alloc] init]; //开始归档 会调用Person对象实现的encodeWithCoder方法 [NSKeyedArchiver archiveRootObject:p toFile:pathFile]; }//取- (IBAction)read:(id)sender { //获取缓存文件路径 NSString *cacheFile = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]; //拼接全路径 NSString *pathFile = [cacheFile stringByAppendingPathComponent:@"data.txt"]; //解档读取数据 会调用Person对象实现的initWithCoder方法返回一个Person对象 Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:pathFile]; NSLog(@"%d", p.age); NSLog(@"%@", p.name);}- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib.}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}@end
0 0
- 归档&存储
- 归档存储
- iOS归档存储数据
- IOS存储对象(归档)
- 数据存储之归档
- 存储方式三 ------------------归档
- NSKeyedArchiver归档存储
- 归档存储子类
- iOS开发归档存储
- ios归档及存储
- 数据存储之归档和反归档
- 通过归档永久存储数据
- 通过归档永久存储数据
- 数据存储----归档解档
- 通过归档永久存储数据
- IOS 对象归档 数据库存储
- 通过归档永久存储数据
- 通过归档永久存储数据
- HDU 5722 Jewelry
- TCP和UDP的主要区别
- 如何调整eclipse字体大小
- android中数据存储的基本
- HUST1017 Exact cover(Dancing Links)Kuangbin模板带解释
- 归档存储
- JavaScript 函数学习笔记
- 网站开发进阶(四十一)中文字体网页开发指南
- window.print()后针式打印机打印出的内容成虚线问题
- 作业
- hd1002 A + B Problem II
- 浅谈HashMap的实现原理
- ACM集训day7
- Nexus 6p 解锁 root 和安装Xposed