Skip to content

Instantly share code, notes, and snippets.

@codelynx
Last active March 21, 2024 08:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save codelynx/0ffab4bd14df1098dcc529bdd1edbfb3 to your computer and use it in GitHub Desktop.
Save codelynx/0ffab4bd14df1098dcc529bdd1edbfb3 to your computer and use it in GitHub Desktop.
Use class_copyPropertyList to extract properties from NSObject based object,
// source:
// https://stackoverflow.com/questions/24750186/i-cant-get-properties-of-a-class-using-swift-by-class-copypropertylist
import Foundation
extension NSObject {
func dictionaryRepresentation() -> [String: Any] {
var count: CUnsignedInt = 0
let properties = class_copyPropertyList(type(of: self), &count)
var dictionary = [String: Any]()
for index in 0 ..< Int(count) {
if let property = properties?[index],
let key = NSString(utf8String: property_getName(property)) as String? {
dictionary[key] = value(forKey: key)
}
}
return dictionary
}
}
/*
import AppKit
let view = NSView(frame: NSRect(x: 0, y: 0, width: 400, height: 300))
print(view.dictionaryRepresentation())
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment