//
// main.m
// 自定义归档
//
// Created by New-World on 13-11-5.
// Copyright (c) 2013年 Gary. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "User.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
User *user=[User new];
user.name=@"laoxu";
user.email=@"xuchina67@163.com";
user.age=22;
user.password=@"123456";
NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"test.plist"];
BOOL success=[NSKeyedArchiver archiveRootObject:user toFile:path];
if (success) {
NSLog(@"归档成功!");
}
[user release];
User *un_user=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"%@",un_user);
}
return 0;
}
///
//
// USer.h
// 自定义归档
//
// Created by New-World on 13-11-5.
// Copyright (c) 2013年 Gary. 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)int age;
@end
/
//
// USer.m
// 自定义归档
//
// Created by New-World on 13-11-5.
// Copyright (c) 2013年 Gary. All rights reserved.
//
#import "User.h"
#define AGE @"age"
#define NAME @"name"
#define EMAIL @"email"
#define PASSWORD @"password"
@implementation User
//对属性进行编码,归档的时候调用
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeInt:_age forKey:AGE];
[aCoder encodeObject:_name forKey:NAME];
[aCoder encodeObject:_email forKey:EMAIL];
[aCoder encodeObject:_password forKey:PASSWORD];
}
//对属性解码,解归档调用
- (id)initWithCoder:(NSCoder *)aDecoder{
self=[super init];
if (self!=nil) {
_age=[aDecoder decodeIntForKey:AGE];
self.name=[aDecoder decodeObjectForKey:NAME];
self.email=[aDecoder decodeObjectForKey:EMAIL];
self.password=[aDecoder decodeObjectForKey:PASSWORD];
}
return self;
}
-(NSString *)description{//输出User时调用的方法
NSString *str=[NSString stringWithFormat:@"\n age=%d \n name=%@ \n email=%@ \n password=%@",_age,_name,_email,_email];
return str;
}
-(void)dealloc{
[_name release];
[_email release];
[_password release];
[super dealloc];
}
@end
OC之自定义归档
最新推荐文章于 2017-03-03 13:38:31 发布