OGeek|极客世界-中国程序员成长平台

标题: ios - 协议(protocol)中的默认实现不适用于我的情况 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:34
标题: ios - 协议(protocol)中的默认实现不适用于我的情况

我在这个例子中模拟了我的情况:

protocol MyProtocol {

    func doSomething()
}

extension MyProtocol {

    func doSomething() {
        print("Do something")
    }
}

class MyViewController: UIViewController, MyProtocol {

    let button = UIButton()

    override func viewDidLoad() {
        super.viewDidLoad()
        button.addTarget(self, action: #selector(doSomething), for: .touchUpInside)
    }
}

我期待 MyViewController 已经实现了 doSomething() 函数,因为它是在 MyProtocol 扩展中实现的。不幸的是,我收到了这个错误:

error: argument of '#selector' refers to instance method 'doSomething()' that is not exposed to Objective-C

我能否修复或解决此问题?



Best Answer-推荐答案


您的协议(protocol)与 Objective-C 不兼容。您需要使用 @objc 对其进行注释,否则您将无法使用选择器,因为方法不会使用 Objective-C 调度。

编辑

所以我应该在写上述内容之前在 Playground 上尝试一下。

您不能将 @objc 函数添加到 Swift 中的协议(protocol)扩展。你必须把它放在类里面。或者你可以扩展 UIViewController 来实现 MyProtocol

例如

@objc protocol MyProtocol 
{
    @objc func doSomething();
} 

extension UIViewController: MyProtocol
{
    @objc func doSomething() { /* implementation */ }   
}

关于ios - 协议(protocol)中的默认实现不适用于我的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43678422/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4