gpt4 book ai didi

ios - Swift 扩展 - 方法与之前使用相同 Objective-C 选择器的声明冲突

转载 作者:搜寻专家 更新时间:2023-10-30 22:59:07 24 4
gpt4 key购买 nike

我正在开发具有 Obj C 代码和 Swift 的 iOS 应用程序。我正在将我现有的 Objective C 类别迁移到 swift 代码。但是当我在快速扩展中覆盖现有方法时,它没有编译。 Swift 扩展适用于新方法,但不适用于覆盖现有方法。

代码:

extension UIViewController {


public override func shouldAutorotate() -> Bool {
return false
}

public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait
}


}

错误:

 Method 'shouldAutorotate()' with Objective-C selector 'shouldAutorotate' conflicts with previous declaration with the same Objective-C selector

Method does not override any method from its superclass

Method 'supportedInterfaceOrientations()' with Objective-C selector 'supportedInterfaceOrientations' conflicts with previous declaration with the same Objective-C selector

在这里,我错过了什么吗?

我正在使用 Xcode 7.3.1Swift 2.x

编辑:

从下面的答案中,我了解到我们不能像在 Objective C 类别中那样在 Swift 扩展中在运行时更改类的现有方法的行为。在这里,我应该创建一个将覆盖方法的基类,并且我应该使用我所有的 ViewControllers 作为新基类作为父类的子类。

但就我而言,我想更改所有“shouldAutorotate”方法的行为,包括第 3 方框架 UIViewController。在上述情况下,我不能强制所有第三方框架 UIviewControllers 成为我的基类的子类。在 Objective C 中我可以做到这一点。

最佳答案

Swift 扩展不用于覆盖在它们扩展的类中声明的方法——尤其是对于 Objective-C 类,这非常类似于在同一类中提供同一方法的两个定义。想象一下看到一个看起来像这样的类:

class UIViewController : UIResponder {
public func shouldAutorotate() -> Bool {
return true
}
public func shouldAutorotate() -> Bool {
return false
}
}

谁赢了?这就是您被警告的冲突。

如果您需要重写您的 View Controller 的方法,您需要在子类中进行,而不是在扩展中进行。

Ninja 编辑:这在 Objective-C 中可能是可行的,但这是一个编程错误。如果类别从主类复制方法,则使用哪个定义是未定义的。参见 this SO postbacking Apple documentation .

关于ios - Swift 扩展 - 方法与之前使用相同 Objective-C 选择器的声明冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37706922/

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