Objective-C基礎 自定義對象歸檔詳解及簡單實例
自定義對象要實現(xiàn)歸檔必須實現(xiàn)NSCoding協(xié)議
NSCoding協(xié)議有兩個方法,encodeWithCoder方法對對象的屬性數(shù)據(jù)做編碼處理,initWithCoder解碼歸檔數(shù)據(jù)來初始化對象。
示例1
.h頭文件
#import <Foundation/Foundation.h> @interface user : NSObject <NSCoding> @property(nonatomic,retain)NSString *name; @property(nonatomic,retain)NSString *email; @property(nonatomic,retain)NSString *pwd; @property(nonatomic,assign)int age; @end
.m實現(xiàn)文件
#import "user.h" #define AGE @"age" #define NAME @"name" #define EMAIL @"email" #define PASSWORD @"password" @implementation user //對屬性編碼 - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeInt:_age forKey:@"age"]; [aCoder encodeObject:_name forKey:AGE]; [aCoder encodeObject:_email forKey:EMAIL]; [aCoder encodeObject:_pwd forKey:PASSWORD]; } //對屬性解碼 - (id)initWithCoder:(NSCoder *)aDecoder { self=[super init]; if(self) { self.age=[aDecoderdecodeIntForKey:AGE]; self.name=[aDecoderdecodeObjectForKey:NAME]; self.email=[aDecoderdecodeObjectForKey:EMAIL]; self.pwd=[aDecoderdecodeObjectForKey:PASSWORD]; } return self; } -(void)dealloc { [_name release]; [_email release]; [_pwd release]; [super dealloc]; } @end
main函數(shù)的調(diào)用
user *userObj=[[user alloc] init]; userObj.age=33; userObj.email=@"adfdadf@qq.com"; userObj.pwd=@"212212"; userObj.name=@"ricard"; NSString *path=[NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/custom.text"]; BOOL succ=[NSKeyedArchiver archiveRootObject:userObj toFile:path]; if (succ) { NSLog(@"Hello, World!"); user *usertemp=[NSKeyedUnarchiver unarchiveObjectWithFile:path]; }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關文章
iOS11實現(xiàn)App內(nèi)自動連接Wi-Fi的方法
這篇文章主要給大家介紹了關于iOS11實現(xiàn)App內(nèi)自動連接Wi-Fi的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-10-10iOS中使用Fastlane實現(xiàn)自動化打包和發(fā)布
Fastlane是一套使用Ruby寫的自動化工具集,用于iOS和Android的自動化打包、發(fā)布等工作,可以節(jié)省大量的時間。下面給大家介紹ios fastlane 自動化打包和發(fā)布的安裝方法,需要的朋友參考下吧2017-05-05iOS 11更新后及iPhone X推出后工程中遇到的問題及適配方法
這篇文章主要介紹了iOS 11更新后及iPhone X推出后工程中遇到的問題及適配,需要的朋友可以參考下2017-10-10iOS 委托與文本輸入(內(nèi)容根據(jù)iOS編程編寫)
這篇文章主要介紹了iOS 委托與文本輸入(內(nèi)容根據(jù)iOS編程編寫) 的相關資料,需要的朋友可以參考下2016-09-09iOS利用UIScrollView實現(xiàn)圖片的縮放實例代碼
本篇文章主要介紹了iOS利用UIScrollView實現(xiàn)圖片的縮放實例代碼,具有一定的參考價值,有興趣的可以了解一下2017-07-07詳解iOS應用中自定義UIBarButtonItem導航按鈕的創(chuàng)建方法
這篇文章主要介紹了iOS應用中自定義UIBarButtonItem導航按鈕的創(chuàng)建方法,文中舉了一個自定義圖片的UIBarButtonItem實例,比較具有代表性,需要的朋友可以參考下2016-04-04