您好,登錄后才能下訂單哦!
平時使用中,我們通常需要通過對自定義對象進行歸檔處理,自定義對象要進行歸檔,需要去實現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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。