【转】IOS数据持久化三个方法:plist、sqlite3、Archiver

1、plist

局限性:只有它支持的数据类型可以被序列化,存储到plist中。无法将其他Cocoa对象存储到plist,更不能将自定义对象存储。

支持的数据类型:Array,Dictionary,Boolean,Data,Date,Number和String.

  xml文件 数据类型截图~其中基本数据(Boolean,Data,Date,Number和String.)、容器 (Array,Dictionary)

写入xml过程:先将基本数据写入容器 再调用容器的 writeToFile 方法,写入。

[theArray writeToFile:filePath atomically:YES];

拥有此方法的数据类型有:

atomically参数,将值设置为 YES。写入文件的时候,将不会直接写入指定路径,而是将数据写入到一个“辅助文件”,写入成功后,再将其复制到指定路径。

2、Archiver

特点:支持复杂的数据对象。包括自定义对象。对自定义对象进行归档处理,对象中的属性需满足:为基本数据类型(int or float or......),或者为实现了NSCoding协议的类的实例。自定义对象的类也需要实现NSCoding。

NSCoding 方法:-(id)initWithCoder:(NSCoder *)decoder; - (void)encodeWithCoder:(NSCoder *)encoder; 参数分别理解为解码者和编码者。

例如创建自定义类Student:NSObject <NSCoding>

1 #import "Student.h"
2
3
4 @implementation Student
5 @synthesize studentID;
6 @synthesize studentName;
7 @synthesize age;
8 @synthesize count;
9
10  - (void)encodeWithCoder:(NSCoder *)encoder
11 {
12 [encoder encodeObject: studentID forKey: kStudentId];
13 [encoder encodeObject: studentName forKey: kStudentName];
14 [encoder encodeObject: age forKey: kAge];
15 [encoder encodeInt:count forKey:kCount]; 
17 }
18
19  - (id)initWithCoder:(NSCoder *)decoder
20 {
21 if (self == [super init]) {
22 self.studentID = [decoder decodeObjectForKey:kStudentId];
23 self.studentName = [decoder decodeObjectForKey:kStudentName];
24 self.age = [decoder decodeObjectForKey:kAge];
25 self.count = [decoder decodeIntForKey:kCount]; 
27 }
28 return self;
29 }
30
31 @end

编码过程:

1 /*encoding*/
2 Student *theStudent = [[Student alloc] init];
3 theStudent.studentID =@"神马";
4 theStudent.studentName =@"shenma";
5 theStudent.age =@"12";
6
7 NSMutableData *data = [[NSMutableData alloc] init];
8 NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
9
10 [archiver encodeObject: theStudent forKey:@"student"];

NSKeyedArchiver可以看作“加密器”,将student实例编码后存储到data

NSMutableData 可看作“容器”,并由它来完成写入文件操作(inherits NSData)。

解码过程:

1 /*unencoding*/
2 Student *studento = [[Student alloc] init];
3 data = [[NSData alloc] initWithContentsOfFile:documentsPath];
4 NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
5
6 studento = [unarchiver decodeObjectForKey:@"student"];
7 [unarchiver finishDecoding];

根据键值key得到反序列化后的实例。

3、SQLite

数据库操作~

原文地址:https://www.cnblogs.com/wengzilin/p/2424944.html