Skip to content

Instantly share code, notes, and snippets.

@billwang1990
Created December 31, 2015 06:32
Show Gist options
  • Save billwang1990/221a926a75be5fb3bdc2 to your computer and use it in GitHub Desktop.
Save billwang1990/221a926a75be5fb3bdc2 to your computer and use it in GitHub Desktop.
dump object properties in swift
import Foundation
extension NSObject {
//
// Retrieves an array of property names found on the current object
// using Objective-C runtime functions for introspection:
// https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html
//
func propertyNames() -> Array<String> {
var results: Array<String> = [];
// retrieve the properties via the class_copyPropertyList function
var count: UInt32 = 0;
var myClass: AnyClass = self.classForCoder;
var properties = class_copyPropertyList(myClass, &count);
// iterate each objc_property_t struct
for var i: UInt32 = 0; i < count; i++ {
var property = properties[Int(i)];
// retrieve the property name by calling property_getName function
var cname = property_getName(property);
// covert the c string into a Swift string
var name = String.fromCString(cname);
results.append(name!);
}
// release objc_property_t structs
free(properties);
return results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment