简体   繁体   中英

How to override a oc category method in .swift

I have a OC UIViewController category , which decleared a class method of UIViewController

+(BOOL)hasStoryBoard;

And I also import this category into xxx-Bridging-Header.h file

My swift class CustomVC is inherited UIViewController. I want override +(BOOL)hasStoryBoard to give a BOOL-type value.This method will called in other class to determine CustomVC 's new instance's some feature.

But in my CustomVC.swift I cannot find method like this:

override class func hasStoryBoard()->bool{}

I must override this method to give a YES ,or give it's subclass a NO ,so on...

I searched this site and find this Swift: How to call a category or class method from Objective-C . In this discussion , explained and tell you how to call the method,not how to override the method .

Can you find solution to override oc category's class method? Or give a workaround in my case.

All my code is :

@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;

defines a class method in Objective-C, but in your Swift subclass you define an instance method:

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

That must be a class method as well:

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

Tip: If you open the Objective-C interface (.h) file in Xcode and select "Navigate->Jump to Generated Interface" from the Xcode menu then you'll see excacly how the Objective-C interface is imported to Swift. In your case:

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

Now you can copy the function definition and use it to define the overriding method in your subclass.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM