-
-
Save hamsternik/4bd3e984cfefd61608e2bc6887477fa5 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
// - Playgorund code here | |
// - This code generates all (private/public) method titles which stored within EAAccessoryManager class | |
import Foundation | |
import ExternalAccessory | |
import PlaygroundSupport | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
/// 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) -> Void) { | |
var ptr = array | |
for i in 0..<count { | |
f(i, ptr.pointee) | |
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(validatingUTF8: 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(array: methodList!, count: methodCount) { (i, m) in | |
let name = methodName(m) ?? "unknown" | |
print("\(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: cls) | |
} | |
else { | |
print("\(classname): no such class") | |
} | |
} | |
print("\nEAAccessoryManager:") | |
printMethodNamesForClass(cls: EAAccessoryManager.self) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment