objective-c - 从 Objective-C 调用 Swift 单例

标签 objective-c singleton swift

我在从 Objective-C 访问 Swift 单例时遇到了一些问题。

@objc class SingletonTest: NSObject {

    // swiftSharedInstance is not accessible from ObjC
    class var swiftSharedInstance: SingletonTest {
    struct Singleton {
        static let instance = SingletonTest()
        }
        return Singleton.instance
    }        
}

无法访问 swiftSharedInstance。

最佳答案

Nicky Goethlis的答案是正确的,但我只想添加另一种创建单例的方式,称为 One line Singleton" 在我最近遇到的 Swift 中,它不使用 Struct:

Singleton.swift

@objc class Singleton: NSObject {

  static let _singletonInstance = Singleton()
  private override init() {
    //This prevents others from using the default '()' initializer for this class.
  }

  // the sharedInstance class method can be reached from ObjC. (From OP's answer.)
  class func sharedInstance() -> Singleton {
    return Singleton._singletonInstance
  }

  // Some testing
  func testTheSingleton() -> String {
    return "Hello World"
  }
}

SomeObjCFile.m

Singleton *singleton = [Singleton sharedInstance];
NSString *testing = [singleton testTheSingleton];
NSLog(@"Testing---> %@",testing);

关于objective-c - 从 Objective-C 调用 Swift 单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24489075/

相关文章:

swift - 无法分配值: Function call returns immutable value

ios - Coredata 对象自动从关系中删除

ios - 为什么不在每个 getter 中使用惰性实例化

php单例在自动加载器类中不断调用自己两次

java - 单例模式

ios - 我想念在 firebase 中解析 JSON 的任何内容吗

iphone - 将图层阴影裁剪为宽度而不是高度?

objective-c - NSDate 将秒数归零而不四舍五入

ios - 单例的良好用例

ios - UIButton 在 collectionView 单元格中不起作用