在 Swift 中的计时器选择器函数中更改 userInfo

hei*_*imi 2 timer userinfo swift

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

用户信息:

var timerDic  = ["count": 0]
Run Code Online (Sandbox Code Playgroud)

定时器:

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

选择器功能:

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

     timer.userInfo["count"] = count
  }
}
Run Code Online (Sandbox Code Playgroud)

我在最后一行出现错误:

“有什么对象吗?” 没有名为“下标”的成员

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

vac*_*ama 5

为了使这项工作,声明timerDicNSMutableDictionary

var timerDic:NSMutableDictionary = ["count": 0]
Run Code Online (Sandbox Code Playgroud)

然后在你的cont_read_USB函数中:

if let timerDic = timer.userInfo as? NSMutableDictionary {
    if let count = timerDic["count"] as? Int {
        timerDic["count"] = count + 1
    }
}
Run Code Online (Sandbox Code Playgroud)

讨论:

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

}
Run Code Online (Sandbox Code Playgroud)

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