[英]UILabel unexpectedly returns nil
Making a basic stopwatch. 制作基本的秒表。 My model is updating my controller fine but when I attempt to update my UILabel
it's returning nil
. 我的模型很好地更新了控制器,但是当我尝试更新UILabel
它返回nil
。
It's only returning nil
when I'm attempting to update from the timer. 当我尝试从计时器更新时,它仅返回nil
。 If I update the controller without using the timer, it will update the label. 如果在不使用计时器的情况下更新控制器,它将更新标签。
I think I must be missing something. 我想我一定很想念东西。
View Controller: 视图控制器:
class ViewController: UIViewController {
var stopWatchBrainInstance = stopWatchBrain()
//Outlets
@IBOutlet weak var timerLabel: UILabel!
var displayValue:Int{
get{
print("getting Display Val")
return Int(timerLabel.text!)!
}
set{
timerLabel?.text! = String(val)
}
}
@IBAction func buttonPressed(_ sender: UIButton) {
if let buttonId = sender.currentTitle{
let testVAr = displayValue
stopWatchBrainInstance.setButton(pressed: buttonId, currentDisplayVal: testVAr)
displayValue = stopWatchBrainInstance.timerVal
}
}
}
Model: 模型:
class stopWatchBrain:NSObject {
//Public API
public func setButton(pressed identifier:String,currentDisplayVal:Int){
switch identifier{
case "Start":
startTimer(currentTime: currentDisplayVal)
break
case "Stop":
stopTimer()
default:
break
}
}
public var timerVal: Int {
get{
return stopwatchValue
}
}
//Vars
private var timer = Timer()
private var stopwatchValue:Int = 1
//Methods
private func startTimer (currentTime: Int){
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(self.runtheTimer)) , userInfo: nil, repeats: true)
}
private func stopTimer (){
print("stopping timer")
timer.invalidate()
}
@objc private func runtheTimer(){
stopwatchValue += 1
print(stopwatchValue)
ViewController().setTitle(stopwatchValue)
}
}
The problem is this line: 问题是这一行:
ViewController().setTitle(stopwatchValue)
Do you know what it does? 你知道它做什么吗? It makes a completely new and separate ViewController object (not the one in the interface), calls its setTitle
method, and throws it away. 它创建了一个全新的独立的ViewController对象(而不是接口中的那个),调用其setTitle
方法并将其丢弃。
Matt gave you the main flaw with your code, although there are some other messes to clean up as well. Matt还为您提供了代码的主要缺陷,尽管还有一些其他问题需要解决。
As for how your StopWatchBrain
would call your view controller, this would be a good use case for the delegate design pattern. 至于StopWatchBrain
如何调用视图控制器,这对于委托设计模式将是一个很好的用例。 Read up on that. 继续阅读。 You'd give your StopWatchBrain
class a delegate that it would call when the value changes. 您将给StopWatchBrain
类一个委托,当值更改时将调用该委托。
You'd make the view controller the delegate of the StopWatchBrain
and it would update it's label when it's delegate method gets called with a new timer value. 您将使视图控制器成为StopWatchBrain
的委托,当使用新的计时器值调用委托方法时,它将更新其标签。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.