您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
自定义对象要实现归档必须实现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]; }
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。