Swift通过IMP调用方法

定义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")
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。