2014-11-02 49 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