切换视图后单例变量变为空

Singleton variable turns empty after switching views

我制作了一个单例 class 以从任何其他 class 访问我用户的电子邮件,以便轻松将数据上传到云。我可以在第一个视图中打印电子邮件,但是当我尝试在其他视图中访问它或返回此视图时,它显示为空。

class SingletonAccount: NSObject {

static var shared: SingletonAccount = SingletonAccount()
var userEmail: String = "ABCD"

}

我还将单例设置为仅在 appDelegate 中初始化,以便它可以在所有其他 classes 之间共享。

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var userAccount: SingletonAccount?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        userAccount = SingletonAccount.shared
        return true
    }

下面是启动时出现的第一个视图控制器

weak var userAccount: SingletonAccount?


    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true

        print(userAccount!.userEmail)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.tapRegister))
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        userAccount = appDelegate.userAccount
        self.registerLbl.addGestureRecognizer(tap)
        // Do any additional setup after loading the view.
    }

您正在视图控制器中声明一个新的 userAccount 实例。如果你必须在 appDelegate 中使用 var

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let aVariable = appDelegate.userAccount

我会一直使用 SingletonAccount.shared。或者在 SingletonAccount class

之外全局定义你的单例
let gSingletonAccount: SingletonAccount = SingletonAccount()
class SingletonAccount: NSObject {
var userEmail: String = "ABCD"
}

单例的好处是可以从任何地方访问同一个实例。

AppDelegate 中声明 属性 毫无意义。只需使用

获取邮件地址
let email = SingletonAccount.shared.userEmail

并声明 shared 为常量。描述 Singleton 暗示一个常量。

static let shared = SingletonAccount()

而且 class 不一定继承自 NSObject,单例也不一定是 class.