1

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.

user4708651
  • 55
  • 1
  • 6

2 Answers2

1

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...

Wain
  • 118,658
  • 15
  • 128
  • 151
1

You cannot change the userInfo object in a timer. userInfo is a readonly property. So the obvious workaround is that you store a mutable object as the userInfo. For example NSMutableDictionary* or your own class.

However, you started with an immutable NSDictionary, and then you converted it to a Swift dictionary. Don't do that. You need direct access to the object that was stored, that is an NSMutableDictionary.

gnasher729
  • 51,477
  • 5
  • 75
  • 98