objective-c自訂類對象的序列化和還原序列化

來源:互聯網
上載者:User

在ios應用中如果需要儲存大對象資料可以採用xml檔案或者屬性檔案方式,但由於採用的純文字方式保密性不夠,如將儲存資料封裝為自訂類的執行個體通過序列化的二進位方式進行儲存,這樣安全性會有所提高。另外後面文章將介紹一些RSA、MD5等演算法對儲存資料進行加密和解密。

具有序列化能力的類必須實現NSCoding協議的兩個函數:

-(void) encodeWithCoder:(NSCoder *)encoder;-(id) initWithCoder:(NSCoder *)decoder;

其中encodeWithCoder函數使自訂對象的各資料欄位序列化,initWithCoder函數使位元據檔案還原序列化為對象執行個體。

例如一個網站的註冊使用者資訊類,包含網站名稱siteName、網站地址siteAddress、註冊使用者名稱userName、登入密碼password、帳戶圖片logoImage。

該資料類的聲明代碼:

#import <Foundation/Foundation.h>@interface RegUserInfo : NSObject <NSCoding> {    NSString *siteName;    NSString *siteAddress;    NSString *userName;    UIImage *logoImage;}@property (nonatomic, strong) NSString *siteName, *siteAddress, *userName;@property (nonatomic, strong) UIImage *logoImage;@end

對資料成員序列化時需要實現- (void)encodeObject:(id)objv forKey:(NSString*)key,如果資料成員是基礎資料型別 (Elementary Data Type)int時,需要使用
- (void)encodeInt:(int)intv forKey:(NSString*)key,encodeWithCoder的具體實現方式如下所示。

-(void) encodeWithCoder:(NSCoder *)encoder {[encoder encodeObject:siteName forKey:@"siteName"];[encoder encodeObject:siteAddress forKey:@"siteAddress"];[encoder encodeObject:userName forKey:@"userName"];[encoder encodeObject:logoImage forKey:@"logoImage"];}

注意:為序列化指定的key值必須保持唯一性,編碼和解碼過程中使用的key必須一致。

對userInfo對象的序列化和還原序列化代碼如下所示。

/*序列化成arch.dat檔案*/[NSKeyedArchiver archiveRootObject:userInfo toFile:@"arch.dat"];/*由檔案arch.dat還原序列化成RegUserInfo對象*/RegUserInfo *newUserInfo = [NSKeyedUnarchiver unarchiveObjectWithFile: @"arch.dat"];

轉帖:http://blog.csdn.net/hsyj_0001/article/details/7594642

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.