Swift中performSelector的替代品? [英] Alternative to performSelector in Swift?
问题描述
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
,类似于Objective-C中的id
.但是,这仍然需要您在编译时对方法名称进行硬编码.有没有办法在运行时动态选择它?
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
更喜欢使用块(比较UIAlertView
,它使用respondsToSelector:
和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的替代品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!