//
// main.m
// 自定义对象的归档
//
// Created by on 14-11-9.
// Copyright (c) 2014年 Apple. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "User.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
/*******归档*******/
User *user = [[User alloc] init];
user.name = @"Tom";
user.email = @"aaa@cc.com";
user.password = @"123";
user.age = 22;
NSString *filePath = @"/Users/wujiafeng/Desktop/archiver";
BOOL success = [NSKeyedArchiver archiveRootObject:user toFile:filePath];
if (success) {
NSLog(@"归档成功");
}
/********解归档********/
User *unUser = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%@", unUser);
}
return 0;
}
//
// User.h
// 自定义对象的归档
//
// Created by on 14-11-10.
// Copyright (c) 2014年 Apple. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface User : NSObject<NSCoding>
@property(nonatomic, copy) NSString *name;
@property(nonatomic, copy) NSString *email;
@property(nonatomic, copy) NSString *password;
@property(nonatomic, assign) NSInteger age;
@end
//
// User.m
// 自定义对象的归档
//
// Created by on 14-11-10.
// Copyright (c) 2014年 Apple. All rights reserved.
//
#import "User.h"
@implementation User
#define NAME @"name"
#define EMAIL @"email"
#define PASSWORD @"password"
#define AGE @"age"
// 对属性编码,归档时候会调用
- (void)encodeWithCoder:(NSCoder *)aCoder {
NSLog(@"对属性编码");
[aCoder encodeObject:_name forKey:NAME];
[aCoder encodeObject:_email forKey:EMAIL];
[aCoder encodeObject:_password forKey:PASSWORD];
[aCoder encodeInteger:_age forKey:AGE];
}
// 对属性解码,解归档时会调用
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
NSLog(@"对属性解码");
_name = [aDecoder decodeObjectForKey:NAME];
_email = [aDecoder decodeObjectForKey:EMAIL];
_password = [aDecoder decodeObjectForKey:PASSWORD];
_age = [aDecoder decodeIntegerForKey:AGE];
}
return self;
}
- (NSString *) description {
NSString *str = [NSString stringWithFormat:@"name=%@, email=%@, password=%@, age=%ld", _name, _email, _password, _age];
return str;
}
@end