swiftobjective-c

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?


Solution

  • 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"];