0

I am creating a swift framework. In that one class is like this as shown below.

 import Foundation
    @objc public class classA: NSObject {

    public override init (){
        super.init();
    }

/**
 Singleton intance is returned.
 */
    public class var sharedInstance: classA {
        struct Static {
            static let instance = popeye();
        }
        return Static.instance
    }
}

Now when i add this framework into a Objective c project and try to access "sharedInstance" i get this error.

Property 'sharedInstance' not found on object of type ClassA. Fix it Replace 'sharedInstance' with 'sharedInstance'

But even if i try use Fix it, this issue isnt solved.

NOTE: This issue doesn't happen when i integrate this framework with a swift project!!!

I AM STUCK.. :(

Abin Anto
  • 1
  • 3

2 Answers2

0

I tried to reproduce your problem. At first the syntax highlighter in Xcode flagged the same error in Objective-C that you mentioned, but the code actually was built and ran fine.

However, there is a cleaner way of doing this. In your code you are using a computed type property, which is evaluated every time you access it! You work around this by introducing the struct Static, where you essentially do what could be done in classA itself, like this:

/**
 Singleton intance is returned.
 */
public static var sharedInstance: classA = popeye()

Here we used a stored type property, which is a recommended way to implement singletons, see here: https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html And here is some documentation on different kinds of properties: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

Anatoli P
  • 4,791
  • 1
  • 18
  • 22
0

Finally i was able to fix this with a minor change !! :)

  • Swift framework code

    @objc class SingletonTest: NSObject {

    // swiftSharedInstance is not accessible from ObjC
    class var swiftSharedInstance: SingletonTest {
    struct Singleton {
        static let instance = SingletonTest()
        }
        return Singleton.instance
    }
    
    // the sharedInstance class method can be reached from ObjC
    class func sharedInstance() -> SingletonTest {
        return SingletonTest.swiftSharedInstance
    }
    
    // Some testing
    func testTheSingleton() -> String {
        return "Hello World"
    }
    

    }

  • Objective C parent project code

    SingletonTest *aTest = [SingletonTest sharedInstance]; NSLog(@"Singleton says: %@", [aTest testTheSingleton]);

Abin Anto
  • 1
  • 3