平時使用中,我們通常需要通過對自定義對象進行歸檔處理,自定義對象要進行歸檔,需要去實現NSCoding協議.
NSCoding協議有兩個方法,encodeWithCoder方法對對象的屬性數據做編碼處理。
initWithCoder方法解碼歸檔數據來進行初始化對象。
實現NSCoding協議後,就能通過NSKeyedArchiver進行歸檔
下面來看下例子代碼:
Person.h頭文件代碼:
#importPerson.m實現代碼:@interface Person : NSObject @property(nonatomic,copy)NSString *name; @property(nonatomic,copy)NSString *email; @property(nonatomic,copy)NSString *password; @property(nonatomic,assign)int age; @end
#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運行截圖:#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; }