Search code examples
swiftobjective-cheaderinterpolationbridging-header

Receiver type '' for instance message is a forward declaration (but header is imported in .m)


I've looked at a lot of posts on this and it usually seems to revolve around missing an import in the .h or the .m

In my case I am trying to import a swift objective C function but I believe the .h, .m and swift files are configured correctly (as is the generated swift-header).

My Swift class is flagged as @objc and extends NSObject.

When I import the class in the .h using forward declaration, and in the .m using the MyApp.h import, it can see the class. However, it cannot see the method I want and it gives me the error Receiver type 'class' for instance message is a forward declaration.

When I check the generated header file, the method is generated there (and the method is flagged as an @objc and returns an @objc compatible value).

Can you suggest what might be causing this issue?

Here is a reference of what my code is like:

Swift

@objc class ObjcHelper: NSObject {
    @objc static let shared = ObjcHelper()

    @objc public func getObjcFromNSString(nsString: NSString) -> ObjcType {
       return ObjcType()
    }
}

In the .h for the objective c file I want to use it in:

@class ObjcHelper

And in the .m I am importing the app header

#import <App-Swift.h>

When I try to use the code in the .m file the compiler can see this part fine:

[ObjcHelper shared] // Compiler sees this fine!

But if I try to call the method it doesn't autocomplete or find it even if I type it in.

If I look in the generated header, I see the method is here like so:

SWIFT_CLASS("_TtC7ObjcHelper")
@interface ObjcHelper : NSObject
SWIFT_CLASS_PROPERTY(@property (nonatomic, class, readonly, strong) ObjcHelper * _Nonnull shared;)
+ (\ObjcHelper * _Nonnull)shared SWIFT_WARN_UNUSED_RESULT;
- (enum ObjcType)getObjcFromNSStringWithNsString:(NSString * _Nonnull)nsString SWIFT_WARN_UNUSED_RESULT;
- (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER;
@end

The code I expect to work that doesn't is as follow (and which generates the error):

ObjcType value = [[ObjcHelper shared] getObjcFromNSStringWithNsString: @"abc"]];


Solution

  • The issue is rather nuanced but it seems to have been solved.

    In my project there are a number of targets and for the ObjcHelper it wasn't targeting one of the targets. I believe what was happening is that even though the bridging objective c helper file was created, there was an issue with a reference missing a 'required' target owner and this error propagates forward as not being able to find the class.

    So if you are getting this issue, check to make sure that the Swift class you are trying to bring into objective-c has its target membership set to all the targets it needs (otherwise you might get a misleading error about forward class declaration).