ios数据存储——对象归档

时间:2023-03-09 05:39:52
ios数据存储——对象归档

归档:数据从内存与闪存相互转化,类似“序列化”,将数据转换成二进制字节数据

操作:有两种方式,第一种是单个对象作为root进行归档和恢复,一个对象一个文件;第二种,可以同时归档多个对象到一个文件

注意:归档自定义对象,需要实现NSCoding协议里的两个方法,举例说明:【preference】http://blog.csdn.net/mad1989/article/details/9106475

一、创建一个数据模型(自定义类)

现在就以大家常见的Student的为例,这个模型有5个参数:name、age、weight、hobby、others

Student.h

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

Student.m

  1. #import "Student.h"
  2. #define knameKey @"name"
  3. #define kageKey @"age"
  4. #define kweightKey @"weight"
  5. #define khobbyKey @"hobby"
  6. #define kotherKey @"others"
  7. @implementation Student
  8. @synthesize name;
  9. @synthesize age;
  10. @synthesize weight;
  11. @synthesize hobby;
  12. @synthesize others;
  13. #pragma mark-NSCoding
  14. -(void)encodeWithCoder:(NSCoder *)aCoder{
  15. [aCoder encodeObject:name forKey:knameKey];
  16. [aCoder encodeInt:age forKey:kageKey];
  17. [aCoder encodeDouble:weight forKey:kweightKey];
  18. [aCoder encodeObject:hobby forKey:khobbyKey];
  19. [aCoder encodeObject:others forKey:kotherKey];
  20. }
  21. -(id)initWithCoder:(NSCoder *)aDecoder{
  22. if (self == [super init]) {
  23. name =  [aDecoder decodeObjectForKey:knameKey];
  24. age = [aDecoder decodeIntForKey:kageKey];
  25. weight =  [aDecoder decodeDoubleForKey:kweightKey];
  26. hobby =  [aDecoder decodeObjectForKey:khobbyKey];
  27. others =  [aDecoder decodeObjectForKey:kotherKey];
  28. }
  29. return self;
  30. }
  31. #pragma mark-NSCopying
  32. -(id)copyWithZone:(NSZone *)zone{
  33. Student *copy = [[[self class] allocWithZone:zone] init];
  34. copy.name = [self.name copyWithZone:zone];
  35. copy.age = self.age;
  36. copy.weight = self.weight;
  37. copy.hobby = [self.hobby copyWithZone:zone];
  38. copy.others = [self.others copyWithZone:zone];
  39. return copy;
  40. }
  41. @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添加几个针对数据模型的可编辑组件:

ios数据存储——对象归档ios数据存储——对象归档

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

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

在ViewDidLoad方法里,每次viewController初始化时,读取路径下的归档文件,读取数据模型数据。同时添加一个通知每当按下Home键时,数据及时归档到闪存中。

  1. - (void)viewDidLoad
  2. {
  3. [super viewDidLoad];
  4. if ([[NSFileManager defaultManager] fileExistsAtPath:[self getFilePath]]) {
  5. NSLog(@"filePAth:%@",[self getFilePath]);
  6. NSData *data = [[NSData alloc] initWithContentsOfFile:[self getFilePath]];
  7. NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
  8. //解档出数据模型Student
  9. Student *mStudent = [unarchiver decodeObjectForKey:kDataKey];
  10. [unarchiver finishDecoding];//一定不要忘记finishDecoding,否则会报错
  11. //接档后就可以直接使用了(赋值到相应的组件属性上)
  12. self.nameLabel.text = mStudent.name;
  13. self.ageLabel.text = [NSString stringWithFormat:@"%d",mStudent.age];
  14. self.weightLabel.text = [NSString stringWithFormat:@"%f",mStudent.weight];
  15. self.hobbyTextField.text = [mStudent.hobby objectAtIndex:0];
  16. self.othersTextView.text = [mStudent.others objectForKey:@"other"];
  17. [unarchiver release];
  18. [data release];
  19. }
  20. //添加一个广播,用于注册当用户按下home键时,归档数据到闪存中
  21. UIApplication *app = [UIApplication sharedApplication];
  22. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveAppDataWhenApplicationWillResignActive) name:UIApplicationWillResignActiveNotification object:app];
  23. }

四、某一操作需要保存数据的时候,及时归档到闪存中

  1. /**
  2. *当用户按下Home键,返回桌面时,归档当前数据到指定文件路径下
  3. */
  4. -(void) saveAppDataWhenApplicationWillResignActive:(NSNotification*) notification{
  5. Student *saveStudent = [[Student alloc] init];
  6. saveStudent.name = self.nameLabel.text;
  7. saveStudent.age = [self.ageLabel.text intValue];
  8. saveStudent.weight = [self.weightLabel.text doubleValue];
  9. saveStudent.hobby = [NSArray arrayWithObjects:self.hobbyTextField.text, nil];
  10. saveStudent.others = [NSDictionary dictionaryWithObjectsAndKeys:self.othersTextView.text,@"other",nil];
  11. NSMutableData *data = [[NSMutableData alloc] init];
  12. NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
  13. [archiver encodeObject:saveStudent forKey:kDataKey];
  14. [archiver finishEncoding];
  15. [data writeToFile:[self getFilePath] atomically:YES];
  16. [data release];
  17. [archiver release];
  18. [saveStudent release];
  19. }

运行效果:

ios数据存储——对象归档重新运行后:ios数据存储——对象归档

归档这种保存方式缺点就是没有属性列表(NSuserDefault)速度快,因为它每次都要把文件保存到闪存中,优点是可以创建自己想要的数据模型,然后统一以模型方式存储,比属性列表要过分依赖Key要省心。