iOS - 无法从 Objective-C 访问 Swift Singleton [英] iOS - Can't access Swift Singleton from Objective-C

查看:65
本文介绍了iOS - 无法从 Objective-C 访问 Swift Singleton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从我的 Objective-C 视图控制器访问我的 Swift 单例类.

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

这是我的 Swift Singleton 类:

@objc class MySingleton : NSObject {静态让共享 = MySingleton()私有覆盖 init() {}}

然后在我的 .m 文件中导入这个标题:

#import "myProject-Swift.h"

并以这种方式使用单例:

 MySingleton *testSingleton = [MySingleton shared];

或者这样:

[MySingleton 共享];

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

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

我做了一个测试功能

func testPrint() {打印(单身工作")}

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

[[MySingleton shared] testPrint];

<块引用>

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

解决方案

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

@objc func testPrint() {打印(单身工作")}

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

[[MySingleton shared] testPrint];

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'

解决方案

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];

这篇关于iOS - 无法从 Objective-C 访问 Swift Singleton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆