平時使用中,我們通常需要通過對自定義對象進行歸檔處理,自定義對象要進行歸檔,需要去實現(xiàn)NSCoding協(xié)議.
NSCoding協(xié)議有兩個方法,encodeWithCoder方法對對象的屬性數(shù)據(jù)做編碼處理。
initWithCoder方法解碼歸檔數(shù)據(jù)來進行初始化對象。
實現(xiàn)NSCoding協(xié)議后,就能通過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實現(xiàn)代碼:
#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函數(shù)代碼:
#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(@"歸檔自定義對象成功."); } //還原數(shù)據(jù) Person *result= [NSKeyedUnarchiver unarchiveObjectWithFile:srcPath]; NSLog(@"name=%@",result.name); NSLog(@"age=%d",result.age); NSLog(@"email=%@",result.email); NSLog(@"password=%@",result.password); } return 0; }運行截圖:
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。