从Swift2开始,你可以使用好的''
class_getMethodImplementation(cls: AnyClass!, _ name: Selector) -> IMP
Run Code Online (Sandbox Code Playgroud)
它回来了imp.在Objective-C你只需要调用它像:
implementation(self, selector)
Run Code Online (Sandbox Code Playgroud)
但是如何在Swift中调用它?
Fab*_*oni 11
基于文章Instance Methods is Curried Functions in Swift,很容易实现所需的结果:
typealias MyCFunction = @convention(c) (AnyObject, Selector) -> Void
let curriedImplementation = unsafeBitCast(implementation, MyCFunction.self)
curriedImplementation(self, selector)
Run Code Online (Sandbox Code Playgroud)
我试图让带有参数的实例方法进行运行时调用.@ Fabio的回答让我大部分都在那里.以下是未来googlers的完整示例:
import Foundation
class X {
@objc func sayHiTo(name: String) {
print("Hello \(name)!")
}
}
let obj = X()
let sel = #selector(obj.sayHiTo)
let meth = class_getInstanceMethod(object_getClass(obj), sel)
let imp = method_getImplementation(meth)
typealias ClosureType = @convention(c) (AnyObject, Selector, String) -> Void
let sayHiTo : ClosureType = unsafeBitCast(imp, ClosureType.self)
sayHiTo(obj, sel, "Fabio")
// prints "Hello Fabio!"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2103 次 |
| 最近记录: |