访问全局 class

Accessing global class

我有一个 class Style,我在我的一个视图控制器中访问它:

class Style {
    static var textSize: CGFloat = 17

    deinit {
        print("i have been deinitiated")
    }
}

当我打开这个视图控制器时,它将 textSize 设置为 30:

class SecondVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        Style.textSize = 30

        let label = UILabel()

        label.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        label.text = "Some text"
        label.font = UIFont.systemFont(ofSize: Style.textSize, weight: .light)

        view.addSubview(label)
    }
}

当我回到我的初始视图控制器并且 SecondVC 被释放时,Style 的 textSize 仍然是 30

class Style 会怎样?当 运行 仪器时,我看不到任何关于 class Style 的信息。我知道 class Style 从未初始化,但是它在哪里保存 textSize 的信息?

搜索swiftstatic,或者阅读Swift程序设计语言(属性),你会得到答案。重要的是 "static"

您在 class Style 中定义了一个 static var,值为 17,现在它存储在 data 中。当Style.textSize = 30被执行时,textSize变成30,当SecondVCdeinit-ed时,不影响textSize因为他们没有关系。 textSize 仍然是 30

当你说 Style.textSize = 30 时,Style 不是 Style() 不是 SecondVC 的 属性,而只是一个 class 参考用于调用静态变量 textSize

如果将 static var textSize: CGFloat = 17 更改为 var textSize: CGFloat = 17,将 Style.textSize = 30 更改为 Style().textSize = 30,您将看到不同之处。

您可能还想阅读 this

如果你想创建 Global class 然后使用 Singleton 而不是 instance:

class Singleton {
    static let sharedInstance = Singleton()
    var textSize = CGFloat()
}

赋值:

Singleton.sharedInstance.textSize = 30

获取值:

let textSize = Singleton.sharedInstance.textSize.count 

通过这样做,您可以确保只有一个实例可以为您的 Singleton 调用,并且您将获得该实例的值。

这是根据 Apple 首选的 Singleton 样式。阅读更多相关信息 here

只要应用程序是 运行,静态变量就永远不会被释放。静电永远存在。一旦设置 style = nil

,下面的代码将调用 deinit
class Style {
  var textSize: CGFloat = 17

  deinit {
    print("i have been deinitiated")
  }
}

class Singleton  {

  static weak var weakReference : Style?
  static var shared: Style {
    get {
      guard let style  = weakReference  else {
          let style = Style()
          weakReference = style
          return style
      }
      return style
      }
    }
}

class SecondVC: UIViewController {

   var str: Style? = Singleton.shared
    override func viewDidLoad() {
        super.viewDidLoad()

        str?.textSize = 30
        str = nil
    }
}