ObjectMapper+RealmSwift

优质
小牛编辑
122浏览
2023-12-01

ObjectMapper + RealmSwift 空值校验

需求, 在通过ObjectMapper解析时, 若value不满足条件整个对象返回nil

  • 演示demo:
import Foundation
import ObjectMapper
import RealmSwift

class TestFModel: Object, Mappable {

    @objc dynamic var version: String?
    @objc dynamic var isOnlie: Bool = false

    // 索引
    override static func indexedProperties() -> [String] {
       return ["version"]
    }

    required convenience init?(map: Map) {
        if !map["isOnline", ignoreNil: true].isKeyPresent
            || !map["Version", ignoreNil: true].isKeyPresent {
            log(" ====> 参数校验失败")
            return nil
        }
        log(" 参数校验通过 ")
        self.init()
    }

    func mapping(map: Map) {
        isOnlie                 <- map["isOnline"]
        version                 <- map["version"]
    }
}
  • 最开始只使用了!map["isOnline"].isKeyPresent来做判定, 发现预期不一致, 翻看了源码

    • 源码

      private func `subscript`(key: String, nested: Bool? = nil, delimiter: String = ".", ignoreNil: Bool = false) -> Map {
          // save key and value associated to it
          currentKey = key
          keyIsNested = nested ?? key.contains(delimiter)
          nestedKeyDelimiter = delimiter
      
          if mappingType == .fromJSON {
              // check if a value exists for the current key
              // do this pre-check for performance reasons
              if keyIsNested {
                  // break down the components of the key that are separated by delimiter
                  (isKeyPresent, currentValue) = valueFor(ArraySlice(key.components(separatedBy: delimiter)), dictionary: JSON)
              } else {
                  let object = JSON[key]
                  let isNSNull = object is NSNull
                  isKeyPresent = isNSNull ? true : object != nil
                  currentValue = isNSNull ? nil : object
              }
      
              // update isKeyPresent if ignoreNil is true
              if ignoreNil && currentValue == nil {
                  isKeyPresent = false
              }
          }
      
          return self
      }
      

      116ignoreNil