2

タイマーが起動するたびに、セレクター関数でタイマーの 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
  }
}

最後の行でエラーが発生します。

「何か?」'subscript' という名前のメンバーがありません

ここで何が問題なのですか?Objective_C では、このタスクNSMutableDictionaryuserInfo

4

2 に答える 2

5

これを機能させるには、次のように宣言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される が毎秒増加します。

于 2014-11-02T12:57:38.463 に答える