Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active July 26, 2023 13:06
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save kristopherjohnson/9759461784c7411788a4 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/9759461784c7411788a4 to your computer and use it in GitHub Desktop.
Get method names for an Objective-C class in Swift
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)
@Jon889
Copy link

Jon889 commented Jun 7, 2023

here's a more to date version for Swift 5.8

/// Print the names for each method in a class
func printMethodNamesForClass(cls: AnyClass) {
	var methodCount: UInt32 = 0
	guard let methodList = class_copyMethodList(cls, &methodCount) else { return }
	for m in UnsafeBufferPointer(start: methodList, count: Int(methodCount)) {
		print(method_getName(m).description)
	}
	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")
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment