iOS – 无法从Objective-C访问Swift Singleton

我无法从Objective-C ViewController访问我的Swift Singleton类

Xcode确实识别我的Swift类,它构建,所以我不认为这是一个桥接头问题。

这是我的Swift Singleton类:

@objc class MySingleton : NSObject { static let shared = MySingleton() private override init() {} } 

然后在我的.m文件中导入此标头:

 #import "myProject-Swift.h" 

并以这种方式使用Singleton:

  MySingleton *testSingleton = [MySingleton shared]; 

或者这样:

 [MySingleton shared]; 

它确实识别MySingleton类类型,但我无法访问此类的任何函数或属性。

我错过了什么? 所有类似的post都没有帮助。

编辑:我做了一个测试function

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

并在objective-c文件中以这种方式调用它:

 [[MySingleton shared] testPrint]; 

没有已知的选择器’testPrint’实例

在你的Swift Singleton类中,为方法testPrint()添加@objc ,如:

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

现在,您从Objective-C类访问该方法:

 [[MySingleton shared] testPrint]; 

testPrint()函数之前使用@objc属性。 参考文件

要在Objective-C中可访问和使用,Swift类必须是Objective-C类的后代,或者必须标记为@objc。