iOS - Can't access Swift Singleton from Objective-C

我只是一个虾纸丫 提交于 2019-12-07 06:46:09

问题


I can't access my Swift Singleton Class from my Objective-C ViewController.

Xcode does recognize my Swift Class, it builds, so I don't think it is a bridging header issue.

Here is my Swift Singleton Class :

@objc class MySingleton : NSObject {

    static let shared = MySingleton()

    private override init() {}
}

And then in my .m file I import this header :

#import "myProject-Swift.h"

And use the Singleton this way :

 MySingleton *testSingleton = [MySingleton shared];

or this way :

[MySingleton shared];

It does recognize the MySingleton class type, but I can't access any functions or properties of this class.

What am I missing? All the similar posts didn't help.

EDIT: I made a test function

func testPrint() {
   print("Singleton worked")
}

And called it this way in the objective-c file :

[[MySingleton shared] testPrint];

No known instance for selector 'testPrint'


回答1:


In your Swift Singleton class, add @objc for the method testPrint() like:

@objc func testPrint() {
   print("Singleton worked")
}

Now, you access the method from Objective-C class:

[[MySingleton shared] testPrint];



回答2:


use @objc attribute before the testPrint() function. refer documentation

To be accessible and usable in Objective-C, a Swift class must be a descendant of an Objective-C class or it must be marked @objc.



来源:https://stackoverflow.com/questions/46949815/ios-cant-access-swift-singleton-from-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!