Objective-C基础 自定义对象归档详解及简单实例
程序员文章站
2024-02-13 23:30:10
自定义对象要实现归档必须实现nscoding协议
nscoding协议有两个方法,encodewithcoder方法对对象的属性数据做编码处理,initw...
自定义对象要实现归档必须实现nscoding协议
nscoding协议有两个方法,encodewithcoder方法对对象的属性数据做编码处理,initwithcoder解码归档数据来初始化对象。
示例1
.h头文件
#import <foundation/foundation.h> @interface user : nsobject <nscoding> @property(nonatomic,retain)nsstring *name; @property(nonatomic,retain)nsstring *email; @property(nonatomic,retain)nsstring *pwd; @property(nonatomic,assign)int age; @end
.m实现文件
#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:age]; [acoder encodeobject:_email forkey:email]; [acoder encodeobject:_pwd forkey: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]; }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!