ios - 如何覆盖 .swift 中的 oc 类别方法

标签 ios objective-c swift

我有一个OC类UIViewController,它声明了UIViewController的一个类方法

+(BOOL)hasStoryBoard;

而且我还把这个类导入到xxx-Bridging-Header.h文件中

我的swift类CustomVC继承了UIViewController。我想覆盖 +(BOOL)hasStoryBoard 以提供一个 BOOL 类型的值。此方法将在其他类中调用以确定 CustomVC 的新实例的某些功能。

但是在我的 CustomVC.swift 中我找不到这样的方法:

覆盖类 func hasStoryBoard()->bool{}

我必须覆盖此方法以提供YES,或为其子类提供NO,依此类推...

我搜索了这个网站并找到了这个 Swift: How to call a category or class method from Objective-C .在此讨论中,解释并告诉您如何调用该方法,而不是如何覆盖该方法。

您能找到覆盖 oc 类别的类方法的解决方案吗? 或者针对我的情况提供解决方法。

我所有的代码是:

@interface UIViewController (StoryBoard)
+(BOOL)hasStoryBoard;
-(void)haha;
@end

.

@implementation UIViewController (StoryBoard)

static BOOL hasStoryboard = NO;//默认没有
+(BOOL)hasStoryBoard{
    return hasStoryboard;
}
-(void)haha{}
@end

.

class CustomVC: UIViewController {
    //this override is correct,have syntax input prompt

    override func haha() {

    }
    //this override is incorrect ,no syntax input prompt

    override func hasStoryBoard()->Bool{
        return true
    }

}

最佳答案

+(BOOL)hasStoryBoard;

在 Objective-C 中定义了一个 class 方法,但是在你的 Swift 子类中 您定义一个实例方法:

override func hasStoryBoard()->Bool{
    return true
}

那也必须是一个类方法:

override class func hasStoryBoard()->Bool{
    return true
}

提示:如果您在 Xcode 中打开 Objective-C 接口(interface) (.h) 文件并 从 Xcode 菜单中选择“Navigate->Jump to Generated Interface” 然后你会清楚地看到 Objective-C 接口(interface)是如何导入到 swift 。在你的情况下:

extension UIViewController {
    open class func hasStoryBoard() -> Bool
    open func haha()
}

现在您可以复制函数定义并使用它来定义 子类中的重写方法。

关于ios - 如何覆盖 .swift 中的 oc 类别方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42736049/

相关文章:

ios - Swift 希望 #selector 的参数暴露给 Objective-C

Objective-C 类方法不调用委托(delegate)方法,而实例方法调用

swift - 无法在新的 Xcode 10.2 (iOS 12.2) 中构建 Alamofire 框架

ios - IBOutlets 在 iOS 8 设备上为零,但在 iOS 9 (Swift) 上工作正常

ios - 如果您在事先同意通知后禁用通知,Apple 如何处理推送 token ?

ios - 将一些数据库引用数据存储在节点键中还是作为值更好?

ios - Xcode 8/ swift 3 : didSelectRowAt vs didSelectRowAtIndexPath

objective-c - 如何阅读苹果开发者网站上的文档?

swift - IAd 横幅广告摇动屏幕

ios - 在 iOS 上使用 SHA256 哈希