ios數據存儲之--對模型對象歸檔(NSKeyedArchiver、NSKeyedUnarchiver)

轉載自:http://blog.csdn.net/mad1989/article/details/9106475


今天記錄一下學習 NSKeyedArchiver、NSKeyedUnarchiver ,主要用在ios數據存儲上,數據從內存存儲到閃存上,這個過程稱爲歸檔。


一、創建一個數據模型(自定義類)

現在就以大家常見的Student的爲例,這個模型有5個參數:name、age、weight、hobby、others


Student.h

  1. #import <Foundation/Foundation.h>  
  2.   
  3. @interface Student : NSObject<NSCoding,NSCopying>  
  4.   
  5. @property(copy,nonatomic) NSString *name;  
  6. @property(assign,nonatomic) int age;  
  7. @property(assign,nonatomic) double  weight;  
  8. @property(copy,nonatomic) NSArray *hobby;  
  9. @property(copy,nonatomic) NSDictionary *others;  
  10.   
  11.   
  12.   
  13. @end  

Student.m

  1. #import "Student.h"  
  2.   
  3.   
  4. #define knameKey @"name"  
  5. #define kageKey @"age"  
  6. #define kweightKey @"weight"  
  7. #define khobbyKey @"hobby"  
  8. #define kotherKey @"others"  
  9.   
  10. @implementation Student  
  11.   
  12. @synthesize name;  
  13. @synthesize age;  
  14. @synthesize weight;  
  15. @synthesize hobby;  
  16. @synthesize others;  
  17.   
  18.   
  19. #pragma mark-NSCoding  
  20. -(void)encodeWithCoder:(NSCoder *)aCoder{  
  21.   
  22.   
  23.     [aCoder encodeObject:name forKey:knameKey];  
  24.     [aCoder encodeInt:age forKey:kageKey];  
  25.     [aCoder encodeDouble:weight forKey:kweightKey];  
  26.     [aCoder encodeObject:hobby forKey:khobbyKey];  
  27.     [aCoder encodeObject:others forKey:kotherKey];  
  28.   
  29. }  
  30.   
  31.   
  32. -(id)initWithCoder:(NSCoder *)aDecoder{  
  33.       
  34.     if (self == [super init]) {  
  35.        name =  [aDecoder decodeObjectForKey:knameKey];  
  36.        age = [aDecoder decodeIntForKey:kageKey];  
  37.        weight =  [aDecoder decodeDoubleForKey:kweightKey];  
  38.        hobby =  [aDecoder decodeObjectForKey:khobbyKey];  
  39.        others =  [aDecoder decodeObjectForKey:kotherKey];  
  40.     }  
  41.       
  42.     return self;  
  43. }  
  44.   
  45.   
  46.   
  47. #pragma mark-NSCopying  
  48. -(id)copyWithZone:(NSZone *)zone{  
  49.     Student *copy = [[[self class] allocWithZone:zone] init];  
  50.     copy.name = [self.name copyWithZone:zone];  
  51.     copy.age = self.age;  
  52.     copy.weight = self.weight;  
  53.     copy.hobby = [self.hobby copyWithZone:zone];  
  54.     copy.others = [self.others copyWithZone:zone];  
  55.       
  56.     return copy;  
  57. }  
  58.   
  59.   
  60. @end  

通過以上的代碼我們可以看出,要實現對數據模型的歸檔,需要我們實現NScoding協議,NScoping(copy協議是爲了模型數據可以複製,對於歸檔而言,不是必須要實現)

NScoding協議需要實現兩個方法:

-(void)encodeWithCoder:(NSCoder *)aCoder    以keyValue形式對基本數據類型Encoding

-(id)initWithCoder:(NSCoder *)aDecoder     以keyValue形式對基本數據類型Decoding,返回數據模型本身

-(id)copyWithZone:(NSZone *)zone      NScopying協議的方法,目的爲了實現數據模型的copy,如下實例:

  1. Student *s1 = [[Student alloc] init];  
  2. Student *s2 = [s1 copy];  
  3. NSLog(@"s1:%@",s1);  
  4. NSLog(@"s2:%@",s2);  

Log控制檯輸出:

2013-06-16 16:19:36.157 ArchiveDemo[1357:c07] s1:<Student: 0x8875340>

2013-06-16 16:19:36.158 ArchiveDemo[1357:c07] s2:<Student: 0x8875360>



二、ViewController.xib添加幾個針對數據模型的可編輯組件:





三、接下來就是在Viewcontroller.m中的操作,首先添加一個內部使用的方法,返回要保存到閃存的位置:

  1. -(NSString *) getFilePath{  
  2.   
  3.     NSArray *array =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
  4.       
  5.      return [[array objectAtIndex:0] stringByAppendingPathComponent:kFileName];  
  6.       
  7. }  


在ViewDidLoad方法裏,每次viewController初始化時,讀取路徑下的歸檔文件,讀取數據模型數據。同時添加一個通知每當按下Home鍵時,數據及時歸檔到閃存中。

  1. - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];  
  4.       
  5.     if ([[NSFileManager defaultManager] fileExistsAtPath:[self getFilePath]]) {  
  6.         NSLog(@"filePAth:%@",[self getFilePath]);  
  7.           
  8.         NSData *data = [[NSData alloc] initWithContentsOfFile:[self getFilePath]];  
  9.           
  10.         NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];  
  11.           
  12.         //解檔出數據模型Student  
  13.         Student *mStudent = [unarchiver decodeObjectForKey:kDataKey];  
  14.         [unarchiver finishDecoding];//一定不要忘記finishDecoding,否則會報錯  
  15.    
  16.         //接檔後就可以直接使用了(賦值到相應的組件屬性上)  
  17.         self.nameLabel.text = mStudent.name;  
  18.         self.ageLabel.text = [NSString stringWithFormat:@"%d",mStudent.age];  
  19.         self.weightLabel.text = [NSString stringWithFormat:@"%f",mStudent.weight];  
  20.         self.hobbyTextField.text = [mStudent.hobby objectAtIndex:0];  
  21.         self.othersTextView.text = [mStudent.others objectForKey:@"other"];  
  22.           
  23.         [unarchiver release];  
  24.         [data release];  
  25.     }  
  26.       
  27.     //添加一個廣播,用於註冊當用戶按下home鍵時,歸檔數據到閃存中  
  28.     UIApplication *app = [UIApplication sharedApplication];  
  29.     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveAppDataWhenApplicationWillResignActive) name:UIApplicationWillResignActiveNotification object:app];  
  30.       
  31. }  


四、某一操作需要保存數據的時候,及時歸檔到閃存中

  1. /** 
  2.  *當用戶按下Home鍵,返回桌面時,歸檔當前數據到指定文件路徑下 
  3.  */  
  4. -(void) saveAppDataWhenApplicationWillResignActive:(NSNotification*) notification{  
  5.       
  6.     Student *saveStudent = [[Student alloc] init];  
  7.     saveStudent.name = self.nameLabel.text;  
  8.     saveStudent.age = [self.ageLabel.text intValue];  
  9.     saveStudent.weight = [self.weightLabel.text doubleValue];  
  10.     saveStudent.hobby = [NSArray arrayWithObjects:self.hobbyTextField.text, nil];  
  11.     saveStudent.others = [NSDictionary dictionaryWithObjectsAndKeys:self.othersTextView.text,@"other",nil];  
  12.       
  13.     NSMutableData *data = [[NSMutableData alloc] init];  
  14.       
  15.     NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];  
  16.       
  17.     [archiver encodeObject:saveStudent forKey:kDataKey];  
  18.       
  19.     [archiver finishEncoding];  
  20.       
  21.     [data writeToFile:[self getFilePath] atomically:YES];  
  22.     [data release];  
  23.     [archiver release];  
  24.     [saveStudent release];  
  25.       
  26.   
  27. }  


運行效果:

重新運行後:


歸檔這種保存方式缺點就是沒有屬性列表(NSuserDefault)速度快,因爲它每次都要把文件保存到閃存中,優點是可以創建自己想要的數據模型,然後統一以模型方式存儲,比屬性列表要過分依賴Key要省心。


目前就記錄這麼多,以後再有的話再補充,如果有什麼錯誤歡迎大家指出,一起學習,進步。


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