首页 > 解决方案 > 单例变量不更新

问题描述

当我尝试通过单例访问它时,下面视图控制器中变量“switcheroo”的值始终相同。我正在尝试从一个一个打印标签字符的自定义标签类中访问它的值。设置标签后,我尝试在 Viewcontroller 单例中获取 switcheroo 的更新值。但是它总是返回 switcheroo 的初始值,而不是更新的值(我可以在视图控制器中跟踪)。难道我做错了什么?

class TheViewController: UITableViewController, UIGestureRecognizerDelegate, UITabBarControllerDelegate {

   static let shared = TheViewController()
   var switcheroo = 0

   ... various operations that change the value of switcheroo...
}

class CustomLabel: UILabel {

  required init?(coder aDecoder: NSCoder) {
     super.init(coder: aDecoder)
  } 

  override var attributedText: NSAttributedString? {

    didSet { 

        DispatchQueue.main.async {

          let characterDelay = TimeInterval(0.01 + Float(arc4random()) / Float(UInt32.max)) / 100

                for (index, _) in attributedText.string.enumerated() {

                    DispatchQueue.main.asyncAfter(deadline: .now() + characterDelay * Double(index)) {
                        print("switcheroo value in TheViewController is now: \(TheViewController.shared.switcheroo)")
                        super.attributedText = attributedText.attributedSubstring(from: NSRange(location: 0, length: index+1))
                    }
                }
            }
}

标签: iosswiftsingleton

解决方案


如果您已经确定使用ViewController单例是正确的决定,那么可能的答案是您不是每次都使用该共享实例,而是在项目中的某个时刻不小心调用了初始化程序(可能 Xcode 正在通过接口自动执行此操作)。

要搜索整个项目,您可以使用 cmd ++ shiftF然后键入TheViewController(). 应该只出现一次(共享实例)。一定要检查TheViewController.init(). 任何时候你都会发现。

如果问题仍然存在,也许尝试selfviewDidLoad方法中将共享实例设置为TheViewController?

希望这可以帮助!


推荐阅读