How do I find all the property keys of a KVC compliant Objective-C object?

后端 未结 5 575
灰色年华
灰色年华 2020-12-13 01:03

Is there a method that returns all the keys for an object conforming to the NSKeyValueCoding protocol?

Something along the lines of [object getPropertyKeys]

5条回答
  •  盖世英雄少女心
    2020-12-13 01:19

    For Swift onlookers, you can get this functionality by utilising the Encodable functionality. I will explain how:

    1. Conform your object to Encodable protocol

      class ExampleObj: NSObject, Encodable {
          var prop1: String = ""
          var prop2: String = ""
      }
      
    2. Create extension for Encodable to provide toDictionary functionality

       public func toDictionary() -> [String: AnyObject]? {
          let encoder = JSONEncoder()
          encoder.outputFormatting = .prettyPrinted
          guard let data =  try? encoder.encode(self),
                let json = try? JSONSerialization.jsonObject(with: data, options: .init(rawValue: 0)), let jsonDict = json as? [String: AnyObject] else {
              return nil
          }
          return jsonDict
      }
      
    3. Call toDictionary on your object instance and access keys property.

      let exampleObj = ExampleObj()
      exampleObj.toDictionary()?.keys
      
    4. Voila! Access your properties like so:

      for k in exampleObj!.keys {
          print(k)
      }
      // Prints "prop1"
      // Prints "prop2"
      

提交回复
热议问题