使用runtime进行解档和归档

首先我们先看一下不用runtime的写法,大家可能感觉很简单为什么要用runtime来实现,但是试想一下如果一个对象有很多很多的属性,我们还要一行一行写吗,和从json中给模型赋值一个道理

传统写法

1
2
3
4
5
6
7
8
9
10
11
// 归档
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: "name")
aCoder.encodeObject(age, forKey: "age")
}
// 解档
required init?(coder aDecoder: NSCoder) {
super.init()
name = aDecoder.decodeObjectForKey("name") as? String
age = aDecoder.decodeObjectForKey("age") as? Int
}

通用写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Model: NSObject, NSCoding {
dynamic var name = ""
dynamic var age = 0
override init() {
}
// 归档
func encode(with aCoder: NSCoder) {
var count: UInt32 = 0
guard let ivars = class_copyIvarList(self.classForCoder, &count) else {
return
}
for i in 0 ..< count {
let ivar = ivars[Int(i)]
let name = ivar_getName(ivar)

let key = NSString.init(utf8String: name!) as! String

if let value = self.value(forKey: key) {
aCoder.encode(value, forKey: key)
}
}
free(ivars)
}
// 解档
required init?(coder aDecoder: NSCoder) {
super.init()
var count: UInt32 = 0
guard let ivars = class_copyIvarList(self.classForCoder, &count) else {
return
}
for i in 0 ..< count {
let ivar = ivars[Int(i)]
let name = ivar_getName(ivar)
let key = NSString.init(utf8String: name!) as! String
if let value = aDecoder.decodeObject(forKey: key) {
self.setValue(value, forKey: key)
}
}
free(ivars)
}
}

  • 使用runtime解档归档的时候一定要在属性前加上dynamic 关键字,并且不能使用可选属性*

######下面我们准备一下要归档的模型和文件路径

1
2
3
4
5
let model = Model()
model.name = "FlyChang"
model.age = 25
var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last
path = path! + "/Model"

归档

1
2
3
4
5
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: data)
archiver.encode(model, forKey: "model")
archiver.finishEncoding()
data.write(toFile: path!, atomically: true)

解档

1
2
3
4
let data = NSData(contentsOfFile: path!)
let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
let model = unarchiver.decodeObject(forKey: "model") as! Model
unarchiver.finishDecoding()

总结了一下使用runtime归档解档的方法,希望能给大家带来帮助~