iOS成长之路

Swift通过IMP调用方法

2020-09-09  本文已影响0人  Red_Wang

定义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")
}
上一篇 下一篇

猜你喜欢

热点阅读