ios - objective c和swift中单例类的使用

标签 ios objective-c swift singleton

我有一个在 Objective C 和 Swift 类中实现的项目,我需要在这些类之间共享全局变量。 我有两个变量 currentUsernamecurrentUsernumber ,我需要在项目的每个 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 中设置和检索 namenumber:

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/

相关文章:

ios - UICollectionViewFlowLayout 的行为未定义

swift - 我如何断言使用最新文本输入的可观察对象的输出

ios - 通过代码 Objective-c 隐藏按钮时出错

ios - 从 SQLite 检索具有多条记录的数据

ios - 在 MPMediaItemPropertyArtwork 中显示的 URL

ios - textFieldShouldReturn - completionHandler 中的一些方法永远不会被调用

objective-c - Xcode MVC 说明

iphone - 在不调用 CGContextFillPath(context) 的情况下添加阴影;

ios - UIView拥有很强的引用性

ios - 分块解密媒体文件并通过 AVPlayer 播放