我有一个在 Objective C 和 Swift 类中实现的项目,我需要在这些类之间共享全局变量。
我有两个变量 currentUsername
和 currentUsernumber
,我需要在项目的每个 View 中使用这两个变量,实现它的最佳方法是什么?
我已经尝试实现单例类,这是我的代码:
class curentUserSingleton {
static var instance: curentUserSingleton!
var currentUsername: String = ""
var currentUsernumber: String = ""
// SHARED INSTANCE
class func sharedInstance(Name : String , Number : String) -> curentUserSingleton {
self.instance = (self.instance ?? curentUserSingleton(uName: Name , uNumber: Number))
return self.instance
}
// METHODS
init(uName : String , uNumber : String) {
self.currentUsername = uName
self.currentUsernumber = uNumber
}}
但是我不知道如何在 OC 和 Swift 中安全地使用这个类,我有点困惑,因为在我的代码中使用这个类时会出现声明错误! 这是编写单例类的正确方法吗?如何用两种语言调用它?
最佳答案
我会倾向于做类似的事情:
class User: NSObject {
static let sharedInstance = User()
var name: String?
var number: String?
}
然后你可以在 Swift 中设置和检索 name
和 number
:
User.sharedInstance.name = "Foo"
User.sharedInstance.number = "42"
print(User.sharedInstance.name)
print(User.sharedInstance.number)
显然,要从 Objective-C .m
文件访问它,您必须像这样包含系统生成的 header :
#import "ModuleName-Swift.h" // obviously, replace `ModuleName` with the name of your module
但是设置和检索这些属性的语法与 Swift 中的语法相似:
[User sharedInstance].name = @"Foo";
[User sharedInstance].number = @"42";
NSLog(@"%@", [User sharedInstance].name);
NSLog(@"%@", [User sharedInstance].number);
关于ios - objective c和swift中单例类的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33974964/