定义TestObject类
import UIKit
class TestObject {
@objc func testMethod(name: String) {
print("Hi \(name)!" )
}
@objc class func testClassMethod(name: String) {
print("Hi \(name)!" )
}
}
调用实例方法
let testObject = TestObject()
let selector = #selector(TestObject.testMethod)
if let method = class_getInstanceMethod(type(of: testObject), selector) {
let imp = method_getImplementation(method)
typealias Function = @convention(c) (AnyObject, Selector, Any?) -> Void
let function = unsafeBitCast(imp, to: Function.self)
function(testObject, selector, "Red")
}
调用类方法
let classSelector = #selector(TestObject.testClassMethod)
if let method = class_getClassMethod(type(of: testObject), classSelector) {
let imp = method_getImplementation(method)
typealias Function = @convention(c) (AnyObject, Selector, Any?) -> Void
let function = unsafeBitCast(imp, to: Function.self)
function(testObject, classSelector, "Red")
}