2014-11-02 65 views
1

我想在每次定时器触发时更新选择器函数中定时器的userInfo。在Swift中更改定时器选择器函数中的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?'没有名为'下标'的成员

这里有什么问题? 在Objective_C这个任务有NSMutableDictionary作为userInfo

回答

4

为了使这项工作,申报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 
    } 
} 

讨论:

  • 斯威夫特字典是值类型,所以如果你希望能够更新它,你必须通过一个对象。通过使用NSMutableDictionary,您将得到一个通过引用传递的对象类型,并且它可以被修改,因为它是可变的字典。雨燕为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

+0

这不适合我。 – 2018-02-26 05:56:09

+0

@AdrianBartholomew,我刚刚在一个Xcode 9.2(最新版)和Swift 4的应用程序中尝试过这个工作。我不得不使用'Timer'而不是'NSTimer'并将'@ objc'添加到定时器更新函数中,但它工作正常。你看到了什么症状? – vacawama 2018-02-26 11:50:30

0

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

但是请注意,这将只修改本地'td'字典,而不是'timerDic'属性(因此在每次*调用时计数为零) – 2014-11-02 11:55:24

+0

@MartinR:您说得对,将引用传递给' timerDic'属性在这里需要。最好修改属性对象本身。 – zisoft 2014-11-02 12:32:57

相关问题