ios - 单例变量不更新
问题描述
当我尝试通过单例访问它时,下面视图控制器中变量“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))
}
}
}
}
解决方案
如果您已经确定使用ViewController
单例是正确的决定,那么可能的答案是您不是每次都使用该共享实例,而是在项目中的某个时刻不小心调用了初始化程序(可能 Xcode 正在通过接口自动执行此操作)。
要搜索整个项目,您可以使用 cmd ++ shift,F然后键入TheViewController()
. 应该只出现一次(共享实例)。一定要检查TheViewController.init()
. 任何时候你都会发现。
如果问题仍然存在,也许尝试self
在viewDidLoad
方法中将共享实例设置为TheViewController
?
希望这可以帮助!
推荐阅读
- spring - 如何使用spring和hibernate从数据库中检索数据并在jsp中打印?
- python - ML 引擎从作曲家失败 - 未知名称“python-version”
- r - 在单个命令中绘制每一行的数据
- kubernetes - kube-dns 服务发现无法发现服务的端口号
- docker - 这个 Dockerfile 语句有什么问题?我应该使用哪一个?
- php - 使用 FPDF 在 Cellfit 上除以零
- c# - 停止并重新启动后,如何使秒表(计时器)从 00:00:00 开始?
- javascript - 在对象中添加另一个具有键值的属性
- c# - Botframework V4:关于输入表单卡片的问题
- linux - 在 CMake 中有条件地查找共享库的依赖项