2

每次定时器触发时,我都想在选择器函数中更新定时器的用户信息。

用户信息:

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

我在最后一行收到错误:

“任何物体?” 没有名为“下标”的成员

这里有什么问题?在 Objective_C 中,此任务使用NSMutableDictionaryasuserInfo

4

2 回答 2

5

为了使这项工作,声明timerDicNSMutableDictionary

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 字典是值类型,所以如果你想能够更新它,你必须传递一个对象。通过使用 anNSMutableDictionary您可以获得一个通过引用传递的对象类型,并且它可以被修改,因为它是一个可变字典。

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打印的内容每秒都会增加。

于 2014-11-02T12:57:38.463 回答
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
        }
    }
}
于 2014-11-02T11:26:24.410 回答