Swift 中 performSelector 的替代方法?

编程入门 行业动态 更新时间:2024-10-26 07:40:25
本文介绍了Swift 中 performSelector 的替代方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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 的替代方法?

本文发布于:2023-11-15 17:28:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1596496.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   Swift   performSelector

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!