Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - Not able to access Static method of swift class

I want to access Swift code in Objective-c.

I have written one class in swift which contains static method. I want to access that Static Method in objective C Class.

Here is 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 made 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 am trying to access it, it is not allowing me to access that static method.

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

Thnaks.

like image 535
NiksT Avatar asked Mar 02 '16 08:03

NiksT


People also ask

How do you call a static method in Swift?

Swift static Methods In Swift, we use the static keyword to create a static method. For example, class Calculator { // static method static func add() { ... } } Here, add() is the static method.

Can we override static method in IOS?

Note: static methods can never be overridden! If you want to override a method, use class instead of static .

What is the difference between class method and static method in Swift?

There is no difference really.

What is static in IOS Swift?

Static variables are those variables whose values are shared among all the instance or object of a class. When we define any variable as static, it gets attached to a class rather than an object. The memory for the static variable will be allocation during the class loading time.


2 Answers

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.

like image 176
Klein Mioke Avatar answered Oct 28 '22 13:10

Klein Mioke


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"];
like image 39
Martin R Avatar answered Oct 28 '22 15:10

Martin R