从NSObject类派生的安全类,用于iOS Swift中的JSON解析

时间:2019-04-09 09:09:15

标签: ios json swift nsobject

在JSON解析中,模型类必须需要符合JSON响应的键编码。因此,遵循以下回答必须有助于防止它在运行时崩溃,并在控制台中打印兼容的丢失密钥。

1 个答案:

答案 0 :(得分:-1)

//
// MARK:- SafeJsonObject
//
@objcMembers
class SafeJsonObject: NSObject {

    override func setValue(_ value: Any?, forKey key: String) {

        let uppercasedFirstCharacter = String(key.first!).uppercased()
        let range = NSMakeRange(0, 1)
        let selectorString = NSString(string: key).replacingCharacters(in: range, with: uppercasedFirstCharacter)

        let selector = NSSelectorFromString("set\(selectorString):")
        let responds = self.responds(to: selector)

        if !responds {
            print("\n\n\n*******--->\(selector) key is missing in API response...<---*******\n\n\n")
            return
        }
        super.setValue(value, forKey: key)
    }
}

PC和参考:https://www.youtube.com/watch?v=3Xv1mJvwXok&list=PL0dzCUj1L5JGKdVUtA5xds1zcyzsz7HLj