-
-
Save eonist/fe253447dfde39fe177ff1bab918bba8 to your computer and use it in GitHub Desktop.
Get method names for an Objective-C class in Swift
This file contains hidden or 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
import Foundation | |
/// Given pointer to first element of a C array, invoke a function for each element | |
func enumerateCArray<T>(array: UnsafePointer<T>, count: UInt32, f: (UInt32, T) -> ()) { | |
var ptr = array | |
for i in 0..<count { | |
f(i, ptr.memory) | |
ptr = ptr.successor() | |
} | |
} | |
/// Return name for a method | |
func methodName(m: Method) -> String? { | |
let sel = method_getName(m) | |
let nameCString = sel_getName(sel) | |
return String.fromCString(nameCString) | |
} | |
/// Print the names for each method in a class | |
func printMethodNamesForClass(cls: AnyClass) { | |
var methodCount: UInt32 = 0 | |
let methodList = class_copyMethodList(cls, &methodCount) | |
if methodList != nil && methodCount > 0 { | |
enumerateCArray(methodList, methodCount) { i, m in | |
let name = methodName(m) ?? "unknown" | |
println("#\(i): \(name)") | |
} | |
free(methodList) | |
} | |
} | |
/// Print the names for each method in a class with a specified name | |
func printMethodNamesForClassNamed(classname: String) { | |
// NSClassFromString() is declared to return AnyClass!, but should be AnyClass? | |
let maybeClass: AnyClass? = NSClassFromString(classname) | |
if let cls: AnyClass = maybeClass { | |
printMethodNamesForClass(cls) | |
} | |
else { | |
println("\(classname): no such class") | |
} | |
} | |
println("NonExistentClass:") | |
printMethodNamesForClassNamed("NonExistentClass") | |
println("\nNSObject:") | |
printMethodNamesForClassNamed("NSObject") | |
println("\nNSString:") | |
printMethodNamesForClass(NSString) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment