objective-C 自定义对象归档的实现
自定义对象要实现归档必须实现NSCoding协议
NSCoding协议有两个方法,encodeWithCoder方法对对象的属性数据做编码处理,initWithCoder解码归档数据来初始化对象。
#import <Foundation/Foundation.h>
@inte易做图ce user : NSObject <NSCoding>
@property(nonatomic,retain)NSString *name;
@property(nonatomic,retain)NSString *email;
@property(nonatomic,retain)NSString *pwd;
@property(nonatomic,assign)int age;
@end
#import "user.h"
#define AGE @"age"
#define NAME @"name"
#define EMAIL @"email"
#define PASSWORD @"password"
@implementation user
//对属性编码
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeInt:_ageforKey:@"age"];
[aCoder encodeObject:_nameforKey:AGE];
[aCoder encodeObject:_emailforKey:EMAIL];
[aCoder encodeObject:_pwdforKey:PASSWORD];
}
//对属性解码
- (id)initWithCoder:(NSCoder *)aDecoder
{
self=[super init];
if(self)
{
self.age=[aDecoderdecodeIntForKey:AGE];
self.name=[aDecoderdecodeObjectForKey:NAME];
self.email=[aDecoderdecodeObjectForKey:EMAIL];
self.pwd=[aDecoderdecodeObjectForKey:PASSWORD];
}
return self;
}
-(void)dealloc
{
[_name release];
[_email release];
[_pwd release];
[super dealloc];
}
@end
main函数的调用
user *userObj=[[user alloc] init];
userObj.age=33;
userObj.email=@"adfdadf@qq.com";
userObj.pwd=@"212212";
userObj.name=@"ricard";
NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/custom.text"];
BOOL succ=[NSKeyedArchiver archiveRootObject:userObj toFile:path];
if (succ) {
NSLog(@"Hello, World!");
user *usertemp=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
}
补充:软件开发 , C语言 ,