【Objective-C】OC中對象歸檔(序列化)的基本概念和用法

概念:歸檔是把對象寫入文件保存在硬盤中,當再次重新打開程序時,可以還原這些對象。

數據持久化的方法:

1:NSKeyedArchiver-對象歸檔

2:NSUserDefaults

3:屬性列表化(NSArray,NSDictonary保存文件)

4:SQlite數據庫,CoreData數據庫

歸檔的形式

1:對Foundation庫中對象進行歸檔

2:自定義對象進行規定(需要實現歸檔協議,NSCoding)

3:歸檔後的文件是加密的,屬性列表是明文的


實例

(一):使用數組爲例,實現數組的歸檔和還原

     主要用到一下兩個類:(NSKeyedArchiver與NSKeyedUnarchiver)的方法

     (1):+ (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path; //進行把對象歸檔到文件當中去

   (2):+ (id)unarchiveObjectWithFile:(NSString *)path;   //根據文件的路徑進行還原內容

     看下面代碼:

#import <Foundation/Foundation.h>    

#import <Foundation/Foundation.h>  int main(int argc, const char * argv[]) {     @autoreleasepool {         NSArray *array=@[@"abc",@"123",@5678];         NSString *homePath=NSHomeDirectory();         NSString *srcPath=[homePath stringByAppendingPathComponent:@"/Desktop/array.archiver"];         BOOL success=[NSKeyedArchiver archiveRootObject:array toFile:srcPath];         if (success) {             NSLog(@"歸檔成功.");         }         //進行還原         NSArray *resultArray= [NSKeyedUnarchiver unarchiveObjectWithFile:srcPath];         NSLog(@"%@",resultArray);     }     return 0; }


自定義內容歸檔:

       歸檔:1:使用NSData實例作爲歸檔的存儲數據

               2:添加歸檔的內容(設置key與value) 

               3:完成歸檔,把歸檔的數據存入到硬盤中

       還原數據:

               1:從硬盤中讀取文件,生成NSData實例

               2:根據Data實例進行創建和初始化還原歸檔文件實例

               3:還原文件,根據key去訪問相應的value值


實例:使用自定義數據類型進行歸檔並且還原數據,看下實現代碼:

      

#import <Foundation/Foundation.h>  int main(int argc, const char * argv[]) {     @autoreleasepool {       //進行自定義對象寫入歸檔       NSString *homePath=NSHomeDirectory();       NSString *srcPath=[homePath stringByAppendingPathComponent:@"/Desktop/custom.archiver"];       NSMutableData *data=[NSMutableData data];       NSKeyedArchiver *archiver=[[NSKeyedArchiver  alloc]initForWritingWithMutableData:data];       [archiver encodeInt:100 forKey:@"key1"];       NSArray *arrary=[NSArray arrayWithObjects:@"tom",@"jack", nil];       [archiver encodeObject:arrary forKey:@"key2"];       [archiver finishEncoding];       [archiver release];        BOOL success= [data writeToFile:srcPath atomically:YES];         if(success){             NSLog(@"寫入成功...");         }              //進行還原數據         NSData *content=[NSData dataWithContentsOfFile:srcPath];         NSKeyedUnarchiver *unarchiver=[[NSKeyedUnarchiver alloc ]initForReadingWithData:content];         NSUInteger result1= [unarchiver decodeIntForKey:@"key1"];         NSArray *result2=[unarchiver decodeObjectForKey:@"key2"];         NSLog(@"還原的數據爲:");         NSLog(@"key1= %ld ",result1);         NSLog(@"key2= %@",result2);      }     return 0; }

   

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章