#import <Foundation/Foundation.h>
@interface user : NSObject<NSCoding>
@property(nonatomic,copy)NSString* name;
@property(nonatomic,copy)NSString* age;
@end
#import "user.h"
@implementation user
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.age forKey:@"age"];
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self.name=[aDecoder decodeObjectForKey:@"name"];
self.age=[aDecoder decodeObjectForKey:@"age"];
return self;
}
@end
#import "ViewController.h"
#import "user.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
user * use=[[user alloc]init];
[email protected]"zefeng";
[email protected]"11";
// 对象归档需要实现这两给方法 归档调用-(void)encodeWithCoder:(NSCoder *)aCoder 解归档 -(id)initWithCoder:(NSCoder *)aDecoder
NSString * path =[NSHomeDirectory() stringByAppendingString:@"use.archiver"];
NSMutableData * data =[NSMutableData data];
NSKeyedArchiver * archive=[[NSKeyedArchiver alloc]initForWritingWithMutableData:data];//二进制存储
[archive encodeObject:use forKey:@"user"];//归档参数
[archive finishEncoding];//结束归档
[data writeToFile:path atomically:YES];//写入路径文件
//读取归档文件
NSData * content =[NSData dataWithContentsOfFile:path];
NSKeyedUnarchiver * unarchiver=[[NSKeyedUnarchiver alloc]initForReadingWithData:content];
user* useData=[unarchiver decodeObjectForKey:@"user"];//根据key 找到对象
NSLog(@"%@",useData.name);
}