【Objective-C】OC中自定义对象的归档基本概念和使用方法(实现NSCoding协议)

平时使用中,我们通常需要通过对自定义对象进行归档处理,自定义对象要进行归档,需要去实现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; @end
Person.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=@"[email protected]";         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; }
运行截图:


你可能感兴趣的:(ios,对象,Objective-C,归档,NSCoding)