Pircate / CleanJSON

Swift JSON decoder for Codable
MIT License
292 stars 40 forks source link

Codable 源码中是如何给model属性赋值的?unbox没找到相关代码,求指导 #5

Closed xsd0720 closed 5 years ago

Pircate commented 5 years ago

image

unbox 先调用的泛型方法, 然后通过 init(from:) -> KeyedDecodingContainerProtocol -> unbox 指定类型, 一步步解码的.

xsd0720 commented 5 years ago

一步步调试 你这个项目, 没有发现例如,setvalue 之类的代码

xsd0720 commented 5 years ago

如果最后设置到model上交给了系统处理, 那哪个方法做到了这一点?是重写了方法,返回了数据?方法触发由系统调用?

Pircate commented 5 years ago

setValue 是在各个类的init(from:)方法里面实现的

Pircate commented 5 years ago

image 这个是 Date 的实现,可以在 Swift 源码里面找到。

xsd0720 commented 5 years ago

self.storage.push(container: value) defer { self.storage.popContainer() } return try type.init(from: self) //这一行触发的?

Pircate commented 5 years ago

self.storage.push(container: value) defer { self.storage.popContainer() } return try type.init(from: self) //这一行触发的?

是的, 这一行会调用各自类的 Decodable 协议的默认实现

Bool 为例:

  1. init(from decoder: Decoder) 里面会执行 container.decode(Bool.self)
  2. 接着调用 unbox(_ value: Any, as type: Bool.Type) throws -> Bool? 就能获取到具体的 Bool 值了

如果自定义 init(from decoder: Decoder) 则会执行自定义的 init(from decoder: Decoder) 方法

xsd0720 commented 5 years ago

了解了,现在的你这个项目 每个model 处理完有没有回调?

Pircate commented 5 years ago

了解了,现在的你这个项目 每个model 处理完有没有回调?

没有回调,同步的不需要。