#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Person *person = [[Person alloc]init];
// person.name = @"jack";
// person.age = 20;
// person.device = @[@"iphone",@"ipad"];
//
// NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"person.archiver"];
// BOOL success = [NSKeyedArchiver archiveRootObject:person toFile:path];
// if (success) {
// NSLog(@"archiver success");
// }
// [person release];
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"person.archiver"];
Person *person = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"%@",person);
}
return 0;
}
#import <Foundation/Foundation.h>
@interface Person : NSObject<NSCoding>
@property (nonatomic,copy)NSString *name;
@property (nonatomic,assign)int age;
@property (nonatomic,copy)NSArray *device;
@end
#import "Person.h"
//定义宏,编辑时易发现错误
#define NAME @"name"
#define AGE @"age"
#define DEVICE @"device"
@implementation Person
//归档时调用
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:_name forKey:NAME];
[aCoder encodeInt:_age forKey:AGE];
[aCoder encodeObject:_device forKey:DEVICE];
}
//解归档时调用
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self != nil) {
self.name = [aDecoder decodeObjectForKey:NAME];
_age = [aDecoder decodeIntForKey:AGE];
self.device = [aDecoder decodeObjectForKey:DEVICE];
}
return self;
}
-(void)dealloc{
[_name release];
[_device release];
[super dealloc];
}
-(NSString *)description {
NSString *str = [NSString stringWithFormat:@"name = %@,age = %d,device = %@",_name,_age,_device];
return str;
}
@end