I use NSTimer to repeat a function every 1 second. I use scheduledTimerWithTimeInterval
method's userInfo
parameter. I need to update data in this userInfo
.
override func viewDidLoad() {
super.viewDidLoad()
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "minus:", userInfo: ["number": 100], repeats: true)
}
func minus(timer: NSTimer) {
var userInfo = timer.userInfo as! Dictionary <String, Int>
println(userInfo["number"]!)
userInfo["number"] = userInfo["number"]! - 1
}
I hope what is printed is 100 99 98 97. But I get 100 100 100 100 when the code is run.
When the function minus
runs for the first time, I think I have changed userInfo's data from 100 to 99. But userInfo
's data is still 100 when function minus
runs for the second time.
How can I update userInfo
's data?
Thank you.
I'm surprised it isn't a build error / crash as the userInfo
is read-only.
You could make it an NSMutableDictionary
so you aren't changing the userInfo
pointer you're just changing the contents of the object it points at, but I'd say really you should just use an instance variable...