3

class_copyPropertyList is giving empty properties in Swift 5 and it was working correct in Swift 3

 extension NSObject {

      func toDictionary(from classType: NSObject.Type) -> [String: Any] {

          var propertiesCount : CUnsignedInt = 0
          let propertiesInAClass = class_copyPropertyList(classType, &propertiesCount)
          let propertiesDictionary : NSMutableDictionary = NSMutableDictionary()

          for i in 0 ..< Int(propertiesCount) {
              let property = propertiesInAClass?[i]
              let strKey = NSString(utf8String: property_getName(property)) as String?
              if let key = strKey {
                  propertiesDictionary.setValue(self.value(forKey: key), forKey: key)
              }
          }
          return propertiesDictionary as! [String : Any]
      }
    }

// call this for NSObject subclass

    let product = Product()
    let dict = product.toDictionary(from: Product.self)
    print(dict)
Aditya Sharma
  • 585
  • 5
  • 18
  • 1
    Probably due to [NSObject `@objc` inference deprecation](https://github.com/apple/swift-evolution/blob/master/proposals/0160-objc-inference.md). You'll want to mark the stored properties as `@objc`, or if you want all members (including methods) exposed to Obj-C, mark the class as `@objcMembers`. See for example https://stackoverflow.com/q/44390378/2976878 – Hamish Mar 26 '19 at 18:55
  • Unrelated, but there's no need to pass in the `classType` parameter, you can use `type(of: self)` instead. Also note that you need to call `free(propertiesInAClass)` before the end of the method to prevent a memory leak. – Hamish Mar 26 '19 at 19:01
  • how can we get property list by using type of – Aditya Sharma Mar 26 '19 at 19:02
  • `class_copyPropertyList(type(of: self), &propertiesCount)` – Hamish Mar 26 '19 at 19:04
  • po class_copyPropertyList(type(of: User.self), &count) error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0). The process has been returned to the state before expression evaluation. – Aditya Sharma Mar 26 '19 at 19:05
  • if self refers to object then also it is crashing – Aditya Sharma Mar 26 '19 at 19:08
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/190719/discussion-between-aditya-sharma-and-hamish). – Aditya Sharma Mar 26 '19 at 19:09

0 Answers0