Swift - 如何将单例设置为 nil [英] Swift - How to set a singleton to nil

查看:142
本文介绍了Swift - 如何将单例设置为 nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 swift 编写一个应用程序,并使用单例在整个应用程序中共享一个类对象 User.我希望能够在用户注销时将此单例设置为nil",以便当他们重新登录时,旧属性不再存在(即名称、用户名等).我希望有一种简单的方法可以将单例设置回 nil,而不必将每个属性设置为 nil.

I am writing an app in swift and use a singleton to share a class object, User, across the app. I want to be able to set this singleton to 'nil' when the user logs out, so that when they log back in the old properties no longer exists (i.e. name, username, etc). I am hoping there is an easy way to just set the singleton back to nil, instead of having to set each property to nil.

这是我在应用程序中用作 User.activeUser 的 User 类:

Here is my User class that is used in the app as User.activeUser:

class User: NSObject
{
    class var activeUser : User? {
        struct Static {
            static let instance : User = User()
        }
        return Static.instance
    }
}

我该如何改变这一点,以便下面的代码不会给我一个警告并且实际上消除了单例对象:

How can I change this so that the below code does not give me a warning and actually nils out the singleton object:

User.activeUser = nil

推荐答案

这应该有效:

private var _SingletonSharedInstance:MyClass! = MyClass()

class MyClass {
  let prop = "test"

  class var sharedInstance : MyClass {
    return _SingletonSharedInstance
  }

  init () {}

  func destroy() {
    _SingletonSharedInstance = nil
  }
}

但是对对象的引用仍然保留,所以你需要做一些额外的事情来使类中的方法调用无效.

But then the references to the object are still kept, so you need to do some additional things to invalidate method calls in the class.

这篇关于Swift - 如何将单例设置为 nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆