【问题标题】:How to call IMP in Swift?如何在 Swift 中调用 IMP?
【发布时间】:2015-09-09 12:58:49
【问题描述】:

由于 Swift2 你可以使用好的 ole':

class_getMethodImplementation(cls: AnyClass!, _ name: Selector) -> IMP

它返回imp。在Objective-C 你可以这样称呼它:

implementation(self, selector)

但是如何在 Swift 中调用它呢?

【问题讨论】:

标签: ios swift


【解决方案1】:

根据文章Instance Methods are Curried Functions in Swift,很容易达到预期的结果:

typealias MyCFunction = @convention(c) (AnyObject, Selector) -> Void
let curriedImplementation = unsafeBitCast(implementation, MyCFunction.self)
curriedImplementation(self, selector)

【讨论】:

  • 稍后会检查它。谢谢!
  • @orkenstein 您可能必须更改 typealias 的类型,因为我不知道您需要什么。
【解决方案2】:

我试图让运行时调用对带有参数的实例方法起作用。 @Fabio 的回答让我大部分时间都在那里。以下是未来谷歌员工的完整示例:

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!"

【讨论】:

  • sayHiTo(obj, sel, "Lou")
  • 调用私有方法:let sel = Selector(("sayHiTo:"))let imp = obj.method(for:sel)
猜你喜欢
  • 1970-01-01
  • 2017-05-01
  • 2012-07-31
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
  • 1970-01-01
  • 2014-09-22
  • 1970-01-01
相关资源
最近更新 更多