performSelector 方法系列 在 Swift 中不可用.那么如何在 @objc 对象上调用方法,其中要调用的方法是在运行时选择的,而在编译时不知道呢?NSInvocation 显然在 Swift 中也不可用.
The performSelector family of methods are not available in Swift. So how can you call a method on an @objc object, where the method to be called is chosen at runtime, and not known at compile time? NSInvocation is apparently also not available in Swift.
我知道在 Swift 中,你可以将任何方法(对于它有一个 @objc 方法声明可见)发送到 AnyObject 类型,类似于 id 在 Objective-C 中.但是,这仍然需要您在编译时对方法名称进行硬编码.有没有办法在运行时动态选择它?
I know that in Swift, you can send any method (for which there is an @objc method declaration visible) to the type AnyObject, similar to id in Objective-C. However, that still requires you to hard-code the method name at compile-time. Is there a way to dynamically choose it at runtime?
推荐答案使用闭包
class A { var selectorClosure: (() -> Void)? func invoke() { self.selectorClosure?() } } var a = A() a.selectorClosure = { println("Selector called") } a.invoke()请注意,这并不是什么新鲜事,即使在 Obj-C 中,新 API 也更喜欢使用块而不是 performSelector(比较使用 respondsToSelector 的 UIAlertView: 和 performSelector: 使用新的 UIAlertController 调用委托方法.
Note that this is nothing new, even in Obj-C the new APIs prefer using blocks over performSelector (compare UIAlertView which uses respondsToSelector: and performSelector: to call delegate methods, with the new UIAlertController).
使用 performSelector: 总是不安全的,并且不能很好地与 ARC 配合使用(因此 performSelector: 的 ARC 警告).
Using performSelector: is always unsafe and doesn't play well with ARC (hence the ARC warnings for performSelector:).
更多推荐
Swift 中 performSelector 的替代方法?
发布评论