我在从 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/