HandyJSON代码阅读

功能:model = modelType.transform(rawdata)

使用分析:

使用机制:继承+实现配置+使用;

需要自己实现什么?

设计分析:

工具模块?机制模块?model基类?

生成机制?

如何组织?

接口:通过继承使用接口;

主干类:

JSONDeserializer<T: HandyJSON>

HandyJSON: _ExtendCustomModelType: _Transformable: _Measurable

_ExtendCustomModelType

mutating func mapping(mapper: HelpingMapper)

mutating func didFinishMapping()

_Transformable

transform(from object: Any) -> Self?

_Measurable

headPointerOfStruct() -> UnsafeMutablePointer<Byte>

问题分解:

1、遍历rawdata对model赋值;

2、赋值解决方案,前提条件:无法获取成员变量的内存引用;

解决方案:kvc赋值(不支持)、根据内存对齐规则直接对内存赋值;

3、对象内存模型信息提取;

4、复杂赋值要处理的情况:

(1)rawdata引用与目标变量名称不一致;

(2)rawdata引用与目标变量路径不一致;

(3)rawdata引用与目标变量类型不一致;

static func _transform(dict: [String: Any], to instance: inout Self) {

        guard let properties = getProperties(forType: Self.self) else {

            InternalLogger.logDebug("Failed when try to get properties from type: (type(of: Self.self))")

            return

        }

        // do user-specified mapping first

        let mapper = HelpingMapper()

        instance.mapping(mapper: mapper)

        // get head addr

        let rawPointer = instance.headPointer()

        InternalLogger.logVerbose("instance start at: ", Int(bitPattern: rawPointer))

        // process dictionary

        let _dict = convertKeyIfNeeded(dict: dict)

        let instanceIsNsObject = instance.isNSObjectType()

        let bridgedPropertyList = instance.getBridgedPropertyList()

        for property in properties {

            let isBridgedProperty = instanceIsNsObject && bridgedPropertyList.contains(property.key)

            let propAddr = rawPointer.advanced(by: property.offset)

            InternalLogger.logVerbose(property.key, "address at: ", Int(bitPattern: propAddr))

            if mapper.propertyExcluded(key: Int(bitPattern: propAddr)) {

                InternalLogger.logDebug("Exclude property: (property.key)")

                continue

            }

            let propertyDetail = PropertyInfo(key: property.key, type: property.type, address: propAddr, bridged: isBridgedProperty)

            InternalLogger.logVerbose("field: ", property.key, "  offset: ", property.offset, "  isBridgeProperty: ", isBridgedProperty)

            if let rawValue = getRawValueFrom(dict: _dict, property: propertyDetail, mapper: mapper) {

                if let convertedValue = convertValue(rawValue: rawValue, property: propertyDetail, mapper: mapper) {

                    assignProperty(convertedValue: convertedValue, instance: instance, property: propertyDetail)

                    continue

                }

            }

            InternalLogger.logDebug("Property: (property.key) hasn't been written in")

        }

    }

原文地址:https://www.cnblogs.com/feng9exe/p/10197081.html