1定义一个AddressCard类,等会将该类实例化一个对象存入NSKeyedArchiver.
//
// AddressCard.h
// NSKeyedArchiverDemo
//
// Created by 罗若文 on 2016/11/2.
// Copyright © 2016年 罗若文. All rights reserved.
// 参考http://www.cnblogs.com/xiaobaizhu/p/4011332.html
/**
归档需要注意的是:
1.同一个对象属性,编码/解码的key要相同!
2.每一种基本数据类型,都有一个相应的编码/解码方法。
如:encodeObject方法与decodeObjectForKey方法,是成对出现的。
3.如果一个自定义的类A,作为另一个自定义类B的一个属性存在;那么,如果要对B进行归档,那么,B要实现NSCoding协议。并且,A也要实现NSCoding协议。
*/
#import <Foundation/Foundation.h>
@interface AddressCard : NSObject<NSCoding>//要用NSKeyedArchiver存储就要申明实现NSCoding协议
@property NSString *name;
@property NSString *email;
@property int salary;
-(void)print;
@end
//
// AddressCard.m
// NSKeyedArchiverDemo
//
// Created by 罗若文 on 2016/11/2.
// Copyright © 2016年 罗若文. All rights reserved.
//
#import "AddressCard.h"
@implementation AddressCard
-(void)print{
NSLog(@"姓名:%@ 邮箱:%@ 薪水:%d",self.name,self.email,self.salary);
}
#pragma mark- ----------NSCoding协议-需要实现以下的encodeWithCoder和initWithCoder都是成对出现.每个属性都要进行设置,对应的key都要相同---------
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.name forKey:@"AddressCard_name"];
[aCoder encodeObject:self.email forKey:@"AddressCard_email"];
[aCoder encodeInt:self.salary forKey:@"AddressCard_salary"];
}
- (id)initWithCoder:(NSCoder *)aDecoder{
self.name=[aDecoder decodeObjectForKey:@"AddressCard_name"];
self.email=[aDecoder decodeObjectForKey:@"AddressCard_email"];
self.salary=[aDecoder decodeIntForKey:@"AddressCard_salary"];
return self;
}
@end
然后接下来就是使用
//
// ViewController.m
// NSKeyedArchiverDemo
//
// Created by 罗若文 on 2016/11/2.
// Copyright © 2016年 罗若文. All rights reserved.
//
#import "ViewController.h"
#import "AddressCard.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor whiteColor]];
//获得文件路径 用来放NSKeyedArchiver
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [documentPath stringByAppendingPathComponent:@"file.archiver"];
AddressCard *obj=[[AddressCard alloc]init];
obj.name=@"luoruowen";
obj.email=@"luoruowen@vip.qq.com";
obj.salary=5000;
BOOL isSuccess=NO;
//将AddressCard对象存入NSKeyedArchiver 这边可以存入任何对象数据,取出来的也是对应的对象数据
isSuccess= [NSKeyedArchiver archiveRootObject:obj toFile:filePath];
if (isSuccess) {
NSLog(@"Success");
}else{
NSLog(@"False");
}
// 反归档 取出AddressCard对象
AddressCard *objTmp=[NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
[objTmp print];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
当然不止存对象, 平常的数据也是可以存储,存入什么取出来的就是什么.