gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 05:20:48 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com