在Swift中更改定时器选择器功能中的userInfo

时间:2014-11-02 10:50:58

标签: swift timer userinfo

我想在每次定时器触发时更新选择器函数中定时器的userInfo。

USERINFO:

var timerDic  = ["count": 0]

计时器:

Init:     let timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector:     Selector("cont_read_USB:"), userInfo: timerDic, repeats: true)

选择器功能:

public func cont_read_USB(timer: NSTimer)
{
  if var count = timer.userInfo?["count"] as? Int
  {
     count = count + 1

     timer.userInfo["count"] = count
  }
}

我在最后一行收到错误:

  

' AnyObject&#39?;没有名为'下标'

的成员

这里有什么问题? 在Objective_C中,此任务使用NSMutableDictionary作为userInfo

2 个答案:

答案 0 :(得分:4)

要完成这项工作,请将timerDic声明为NSMutableDictionary

var timerDic:NSMutableDictionary = ["count": 0]

然后在cont_read_USB函数中:

if let timerDic = timer.userInfo as? NSMutableDictionary {
    if let count = timerDic["count"] as? Int {
        timerDic["count"] = count + 1
    }
}

讨论:

  • Swift词典是值类型,因此如果您希望能够更新它,则必须传递一个对象。通过使用NSMutableDictionary,您将获得通过引用传递的对象类型,并且可以对其进行修改,因为它是可变字典。

Swift 4 +的完整示例:

如果您不想使用NSMutableDictionary,则可以创建自己的class。以下是使用自定义class的完整示例:

import UIKit

class CustomTimerInfo {
    var count = 0
}

class ViewController: UIViewController {

    var myTimerInfo = CustomTimerInfo()

    override func viewDidLoad() {
        super.viewDidLoad()

        _ = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(update), userInfo: myTimerInfo, repeats: true)
    }

    @objc func update(_ timer: Timer) {
        guard let timerInfo = timer.userInfo as? CustomTimerInfo else { return }

        timerInfo.count += 1
        print(timerInfo.count)
    }

}

在模拟器中运行时,打印的count每秒都会增加。

答案 1 :(得分:1)

NSTimer.userInfo的类型为AnyObject,因此您需要将其强制转换为目标对象:

public func cont_read_USB(timer: NSTimer)
{
    if var td = timer.userInfo as? Dictionary<String,Int> {
        if var count = td["count"] {
            count += 1
            td["count"] = count
        }
    }
}