NiksT
NiksT

Reputation: 281

Unable to access static method of Swift class from Objective-C

I want to access Swift code in Objective-C.

I have written one class in Swift which contains a static method. I want to access that static method in an Objective-C class.

Here is the class declaration:

@objc class LocalizedResource: NSObject {
    /*!
    * @discussion This function will get localize string for key

    * @param key Localize key
    * @return String for locaized key
    * @code LocalizedResource.getStringForKey(key);
    */
    static func getStringForKey(key:String) -> String    {
        let frameworkBundle = NSBundle.mainBundle()
        let value = frameworkBundle.localizedStringForKey(key, value: nil, table: nil)
        return value;
    }
}

I have set the following settings for it:

  1. Product Module Name : MyProject
  2. Defines Module : YES
  3. Embedded Content Contains Swift : YES
  4. Install Objective-C Compatibility Header : YES
  5. Objective-C Bridging Header : $(SRCROOT)/MySources/SwiftBridgingHeader.h

Also I have added @obj before my class declaration in Swift class.

I have import MyProject-Swift.h in the .m file where I want to access that method.

But when I try to access it, it is not allowing me to access that static method. Here is the Objective-C code:

errorMessage.text =  LocalizedResource.getStringForKey(@"TIMED_OUT_ERROR");

It is giving me the error:

Property 'getStringForKey' not found on object of type 'LocalizedResource'

Is any one having solution for it? Is there something missing?

Upvotes: 20

Views: 19444

Answers (3)

Anton Tropashko
Anton Tropashko

Reputation: 5806

I forgot to add public for class and public/open for the method so it was not present in -Swift.h and not accessible outside of the framework that defined it

Upvotes: 0

Klein Mioke
Klein Mioke

Reputation: 1352

Note in Swift 4 and the build setting swift 3 @objc inference is default, we must explicitly mark function as @objc, or it will not generate class function in Swift bridge header.

Upvotes: 37

Martin R
Martin R

Reputation: 539685

From your comment:

I am calling this method as follows:

errorMessage.text = LocalizedResource.getStringForKey(@"TIMED_OUT_ERROR");

In Objective-C, the "dot syntax" is used for properties, not for methods. The correct call should be

errorMessage.text = [LocalizedResource getStringForKey:@"TIMED_OUT_ERROR"];

Upvotes: 14

Related Questions