gpt4 book ai didi

swift - 尝试快速将选择器调用到静态函数

转载 作者:搜寻专家 更新时间:2023-11-01 06:12:13 25 4
gpt4 key购买 nike

我正在努力实现以下目标,但遇到了问题:-)

  • 创建 UIViewController 和 UIView 子类可以采用的协议(protocol)其中包含一个要在此类上调用的静态方法(将其称为配置
  • 然后我想使用 objectiveC 运行时来查找采用此协议(protocol)的类
  • 我想在每个类上调用配置方法
  • 配置方法是返回一个字典(key:描述字符串,value:类上要调用的选择器)

到目前为止,我能够创建协议(protocol),找到实现该协议(protocol)的类,但我遇到了编译问题。

这是协议(protocol)

@objc public protocol MazeProtocol: NSObjectProtocol{
@objc static func configurations() -> NSDictionary
}

这是在我的一个类(class)上采用协议(protocol)的扩展:

extension MapCoordinatorViewController: MazeProtocol {

static func configurations() -> NSDictionary {
let returnValue = NSMutableDictionary()
returnValue.setObject(#selector(test), forKey: "test" as NSString)
return returnValue
}

@objc static func test() {

print("test")
}}

这是我用来尝试调用从配置方法返回的选择器的代码:

let selectorKey = controllerClass.configurations().allKeys[indexPath.row]
let selector = controllerClass.configurations().object(forKey: selectorKey)
controllerClass.performSelector(selector) <================ error here

ControllerClass 声明为 let controllerClass: MazeProtocol.Type

我收到以下编译警告:实例成员“performSelector”不能用于类型“MazeProtocol”

我错过了什么?

最佳答案

您可以在技术上强制执行此操作。请不要。这是可怕的 swift 。为了让它发挥作用,你必须破坏 Swift 试图做的一切。但是,是的,有了警告,你可以在技术上让它编译和工作。请,请不要。

首先,您需要使selector 成为Selector。您正在使用 NSDictionary,这在 Swift 中很糟糕,所以您得到 Any? 返回。但是,是的,您可以 as! 将其转换为您想要的内容:

let selector = controllerClass.configurations().object(forKey: selectorKey) as! Selector

然后,无视所有的类型神,你可以声明类实际上是 NSObjectProtocol,因为为什么不呢?

(controllerClass as! NSObjectProtocol).perform(selector)

这将抛出警告“从‘MapCoordinatorViewController.Type’到无关类型‘NSObjectProtocol’的转换总是失败”,但它实际上会成功。

毕竟“不要这样做”,你应该怎么做呢?有闭包。

public protocol MazeProtocol {
static var configurations: [String: () -> Void] { get }
}

class MapCoordinatorViewController: UIViewController {}

extension MapCoordinatorViewController: MazeProtocol {

static let configurations: [String: () -> Void] = [
"test": test
]
static func test() {
print("test")
}
}


let controllerClass = MapCoordinatorViewController.self
let method = controllerClass.configurations["test"]!
method()

关于swift - 尝试快速将选择器调用到静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53502451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com