关于 含有模型数据的可变字典 持久化存储

我要永远地记住你!(iOS中几种数据持久化方案)



NSKeyedArchiver

归档在iOS中是另一种形式的序列化,只要遵循了NSCoding协议的对象都可以通过它实现序列化。由于决大多数支持存储数据的Foundation和Cocoa Touch类都遵循了NSCoding协议,因此,对于大多数类来说,归档相对而言还是比较容易实现的。

1.遵循NSCoding协议

NSCoding协议声明了两个方法,这两个方法都是必须实现的。一个用来说明如何将对象编码到归档中,另一个说明如何进行解档来获取一个新对象。

遵循协议和设置属性

//1.遵循NSCoding协议@interfacePerson: NSObject //2.设置属性@property(strong, nonatomic) UIImage *avatar;@property(copy, nonatomic) NSString *name;@property(assign, nonatomic) NSInteger age;@end

实现协议方法

//解档- (id)initWithCoder:(NSCoder *)aDecoder {if([superinit]) {          self.avatar = [aDecoderdecodeObjectForKey:@"avatar"];          self.name = [aDecoderdecodeObjectForKey:@"name"];          self.age = [aDecoderdecodeIntegerForKey:@"age"];      }returnself;  }//归档- (void)encodeWithCoder:(NSCoder *)aCoder {      [aCoderencodeObject:self.avatarforKey:@"avatar"];      [aCoderencodeObject:self.nameforKey:@"name"];      [aCoderencodeInteger:self.ageforKey:@"age"];  }

特别注意

如果需要归档的类是某个自定义类的子类时,就需要在归档和解档之前先实现父类的归档和解档方法。即[super encodeWithCoder:aCoder]和[super initWithCoder:aDecoder]方法;

2.使用

需要把对象归档是调用NSKeyedArchiver的工厂方法archiveRootObject: toFile:方法。

NSString *file =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"person.data"];Person*person=[[Person alloc]init];person.avatar = self.avatarView.image;person.name = self.nameField.text;person.age =[self.ageField.text integerValue];[NSKeyedArchiver archiveRootObject:person toFile:file];

需要从文件中解档对象就调用NSKeyedUnarchiver的一个工厂方法unarchiveObjectWithFile:即可。

NSString*file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).firstObject stringByAppendingPathComponent:@"person.data"];  Person *person = [NSKeyedUnarchiverunarchiveObjectWithFile:file];if(person) {self.avatarView.image = person.avatar;self.nameField.text = person.name;self.ageField.text = [NSStringstringWithFormat:@"%ld", person.age];  }

3.注意

必须遵循并实现NSCoding协议

保存文件的扩展名可以任意指定

继承时必须先调用父类的归档解档方法

你可能感兴趣的:(关于 含有模型数据的可变字典 持久化存储)