美文网首页iOS成长之路
Swift通过IMP调用方法

Swift通过IMP调用方法

作者: Red_Wang | 来源:发表于2020-09-09 12:04 被阅读0次

    定义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")
    }
    

    相关文章

      网友评论

        本文标题:Swift通过IMP调用方法

        本文链接:https://www.haomeiwen.com/subject/twreektx.html