您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
平时使用中,我们通常需要通过对自定义对象进行归档处理,自定义对象要进行归档,需要去实现NSCoding协议.
NSCoding协议有两个方法,encodeWithCoder方法对对象的属性数据做编码处理。
initWithCoder方法解码归档数据来进行初始化对象。
实现NSCoding协议后,就能通过NSKeyedArchiver进行归档
下面来看下例子代码:
Person.h头文件代码:
#import <Foundation/Foundation.h> @interface Person : NSObject <NSCoding> @property(nonatomic,copy)NSString *name; @property(nonatomic,copy)NSString *email; @property(nonatomic,copy)NSString *password; @property(nonatomic,assign)int age; @endPerson.m实现代码:
#import "Person.h" #define AGE @"age" #define NAME @"name" #define EMAIL @"email" #define PASSWORD @"password" @implementation Person //对对象属性进行编码方法 - (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]; _name=[[aDecoder decodeObjectForKey:NAME]copy]; _email=[[aDecoder decodeObjectForKey:EMAIL]copy]; _password=[[aDecoder decodeObjectForKey:PASSWORD]copy]; } return self; } -(void)dealloc{ [_name release]; [_email release]; [_password release]; [super dealloc]; }main.m函数代码:
#import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { Person *person=[[Person alloc]init]; person.name=@"jack"; person.age=20; person.email=@"jack@163.com"; person.password=@"12345"; NSString *homePath=NSHomeDirectory(); NSString *srcPath=[homePath stringByAppendingPathComponent:@"Desktop/person.archiver"]; BOOL success=[NSKeyedArchiver archiveRootObject:person toFile:srcPath]; if (success) { NSLog(@"归档自定义对象成功."); } //还原数据 Person *result= [NSKeyedUnarchiver unarchiveObjectWithFile:srcPath]; NSLog(@"name=%@",result.name); NSLog(@"age=%d",result.age); NSLog(@"email=%@",result.email); NSLog(@"password=%@",result.password); } return 0; }运行截图:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。