Search code examples
objective-cswiftobject-initializers

Using Swift object class in Objective-C


Hello I have been looking at different questions regarding this and none of the solution seem to work for me. I have an object which I am trying to use in objective C, however I keep getting the 'No visible interface for object' when trying to initialize the object. I have properly imported my module into the objective C file and added the @objc annotation am i missing something? thank you in advance!

Code:

Swift-

import UIKIT

@objc class SaveFile: NSOBject {
 var name: String?
 var location: String?

//@objc(initId:andSize:) does not work
init(id: String, size: String) {
    super.init()
   //other code
}

}

Objective C -

    import "testProject-Swift.h"

// functions and initializers

-(void) saveFile {
    SaveFile *fileToSave = [[SaveFile alloc] initWithId:self.currentId size:self.size] //No visible @interface for 'SaveFile' declares the selector 'initWithId:Size:'

}

Solution

  • Try this:

    @objcMembers
    class SaveFile: NSObject {//<-NSObject, not NSOBject
        var name: String?
        var location: String?
    
        init(id: String, size: String) {
            super.init()
            //other code
        }
    
    }
    

    When you write a class which is used in Objective-C code, it's an easy way to annotate with @objcMembers.

    Or else, you can annotate all properties and methods including initializers with @objc:

    class SaveFile: NSObject {
        @objc var name: String?
        @objc var location: String?
    
        //@objc(initWithId:size:) do work
        @objc init(id: String, size: String) {
            super.init()
            //other code
        }
    }