Objective-C基础 自定义对象归档详解及简单实例

时间:2021-05-02

自定义对象要实现归档必须实现NSCoding协议

NSCoding协议有两个方法,encodeWithCoder方法对对象的属性数据做编码处理,initWithCoder解码归档数据来初始化对象。

示例1

.h头文件

? 1 2 3 4 5 6 7 #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实现文件

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 #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函数的调用

? 1 2 3 4 5 6 7 8 9 10 11 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]; }

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章