Last active
March 21, 2024 08:22
-
-
Save codelynx/0ffab4bd14df1098dcc529bdd1edbfb3 to your computer and use it in GitHub Desktop.
Use class_copyPropertyList to extract properties from NSObject based object,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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