// Person *person = [[Person alloc] init];
// person.age = 16;
// person.name = @"tom";
// person.sex = @"male";
//
// [person description];
//
// NSData *data = [NSKeyedArchiver archivedDataWithRootObject:person];
//
// NSLog(@"%hhd", [data writeToFile:@"/Users/zzj/desktop/test/person.data" atomically:YES]);
NSData *data = [NSData dataWithContentsOfFile:@"/Users/zzj/desktop/test/person.data"];
Person *person = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[person description];
@implementation Person
//解码
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self){
_name = [aDecoder decodeObjectForKey:@"name"];
_age = [aDecoder decodeIntegerForKey:@"age"];
_sex = [aDecoder decodeObjectForKey:@"sex"];
}
return self;
}
//编码
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:_name forKey:@"name"];
[aCoder encodeInteger:_age forKey:@"age"];
[aCoder encodeObject:_sex forKey:@"sex"];
}
#import <Foundation/Foundation.h>
//实现NSCoding协议
@interface Person : NSObject<NSCoding>
@property(nonatomic, copy) NSString *name;
@property(nonatomic, assign) NSUInteger age;
@property(nonatomic, copy) NSString *sex;
@end