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

标签 ios objective-c swift singleton swift4

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

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

这是我的 Swift 单例类:

@objc class MySingleton : NSObject {

    static let shared = MySingleton()

    private override init() {}
}

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

#import "myProject-Swift.h"

并以这种方式使用单例:

 MySingleton *testSingleton = [MySingleton shared];

或者这样:

[MySingleton shared];

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

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

编辑:我做了一个测试函数

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

并在 objective-c 文件中这样调用它:

[[MySingleton shared] testPrint];

No known instance for selector 'testPrint'

最佳答案

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

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

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

[[MySingleton shared] testPrint];

关于iOS - 无法从 Objective-C 访问 Swift Singleton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46949815/

相关文章:

ios - fetchBachSize 是真的有必要还是有缺陷被替代呢?

objective-c - 在具有 NSDictionary 定义的程序中迷路 @

ios - 是否可以保存WKWebview内容供离线阅读?

ios - 找不到接受提供的参数的重载 "init'

ios - 如何在 XIB 中调用 UITextField 的委托(delegate)方法?

ios - 在 iOS 8 上调用系统共享菜单

cocoa-touch - UINavigationBar 右键不显示

ios - Swift 中的 Web View

ios - 在添加到 UIWindow 的 View 上使用自动布局

objective-c - 在 iPhone 应用程序中使用 UiWebView(用于支付)会被拒绝吗?应用程序是一种网络服务