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