美文网首页
Swift动态调用方法

Swift动态调用方法

作者: Fintecher | 来源:发表于2019-03-01 17:47 被阅读0次
//动态调用方法
//    let selector = NSSelectorFromString("searchBarShouldBeginEditing:")
//    if let delegate = searchBarDelegate {
//        if let method = extractMethodFrom(owner: searchBarDelegate!, selector: selector) {
//            method(searchBar)
//        }
//    }
    func extractMethodFrom(owner: AnyObject, selector: Selector) -> ((Any?) -> Any)? {
        let method: Method?
        if owner is AnyClass {
            method = class_getClassMethod(owner as? AnyClass, selector)
        } else {
            print(type(of: owner))
            method = class_getInstanceMethod(type(of: owner), selector)
        }
        
        if let one = method {
            let implementation = method_getImplementation(one)
            
            typealias Function = @convention(c) (AnyObject, Selector, Any?) -> Void
            
            let function = unsafeBitCast(implementation, to: Function.self)
            
            return { userinfo in function(owner, selector, userinfo) }
            
        } else {
            return nil
        }
    }

相关文章

网友评论

      本文标题:Swift动态调用方法

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