objective-cswiftxcode10objective-c-category

Swift code cannot see method declared in Objective-C category


I have a very simple Swift objc class from which I want to call a method that is defined in a category of a class defined in Objective-C.

However, the compiler is not happy:

.../UploadOperation.swift:25:24: error: value of type 'MyServer' has no member 'clearPendingData'
        self.server?.clearPendingData();

When I move the declaration of clearPendingData to the main class declaration, the compiler is happy (except I now get warnings in my Objective-C code about the main class vs category method implementations).

Here is the Swift declaration, in file UploadOperation.swift

@objc class UploadOperation: Operation {

    @objc var server: MyServer? = nil

    override init() {
        super.init()
        self.completionBlock = { [unowned self] () in
            self.server?.clearPendingData()
        }
    }
}

And here is the category, in file MyServer+upload.h:

#import "MyServer.h"

@class UploadOperation;

@interface MyServer (upload)
    - (void) clearPendingData;
@end

And the main class declaration, in file MyServer.h

@interface MyServer : NSObject
    - (MyServer *) init;
    // and a ton of stuff omitted
@end

(of course, a lot of irrelevant code omitted)

This is with Xcode 10.1.

What gives? Thanks


Solution

  • If you wish to access Objective-C methods from Swift defined in a category you must included the category header as well as the class header in your bridging file. In this case include MyServer+upload.h as well as MyServer.h. Your error suggests you haven't done this. HTH