2016-09-23 5 views
0
によりキャッチされない例外 'NSInvalidArgumentException'、理由にアプリを終了
Timer.scheduledTimer(timeInterval: 5.0, target:self.notificationView, selector: #selector(NotificationView.self.timerFired(_:)), userInfo: nil, repeats: false) 

func timerFired(_ timer: Timer) { 
     print("Timer Fired") 
} 

***: -スイフト3.0:タイマは、自己以外の標的の焼成ない

'認識されていないセレクタがインスタンス0x7fc0baf46f60に送ら[_ SwiftValue timerFired:] [

どこが間違っているのですか?ターゲットが自己であれば、すべて正常に動作します。

+0

これはおそらくこれです:http://stackoverflow.com/questions/39622721/how-initialize-a-timer-inside-a-custom-class-in-swift? –

答えて

0

チェックエラー・メッセージのこの部分:

[_SwiftValue timerFired:]

timerFired:セレクタのObjective-Cの形式の表記です。あなたの#selector(...)が機能しているようです。 (推奨しませんが...)

_SwiftValueは、セレクタの対象となるオブジェクトのクラス名です。つまり、target:self.notificationViewのターゲットは_SwiftValueに変換されます。

これは、notificationViewをオプションまたは暗黙のアンラップとして宣言すると発生する可能性があります。もしそうなら、これを試してみてください。

Timer.scheduledTimer(timeInterval: 5.0, target: self.notificationView!, selector: #selector(NotificationView.timerFired(_:)), userInfo: nil, repeats: false) 

(。self.notificationView!を逃さないようにしてください)

+0

ありがとうございます。これは実際には愚かなことではありません。出来た。 –

+0

@PawanKumarSingh、コンパイラはこの種の間違いを検出し、私たちに警告するはずです。多くの開発者はこの '_SwiftValue'のことで苦しんでいます。それをバグと呼び、[Apple](http://developer.apple.com/bug-reporting/)にバグ報告を送ることができます。 – OOPer

1

問題はあなたのselector構文と同じです。

#selector(NotificationView.timerFired(_:)) 

注:selfはあなたが別のアクションを設定したいならば、あなたはそれがNotificationView.timerFiredで、あなたのケースでclass name.methodを指定する必要があり、現在のViewControllerためです。

+0

どちらも同じです。質問を投稿する前に両方のコードを試しました。私はそのswift3.0のバグだと思う。 Timer.scheduledTimer(timeInterval:5.0、target:self.notificationView、selector:#セレクタ(NotificationView.timerFired(_ :))、userInfo:nil、繰り返し:false) –

+0

マーティンRが提案したようにしてみましたか? –

1

私は、次のコードを試してみて、をNotificationView.timerFiredトリガーされます。

class NotificationView { 
    @objc func timerFired(_ timer: Timer) { 
    print("Timer Fired") 
    } 
} 

class ViewController: UIViewController { 
    let notificationView = NotificationView() 

    override func viewDidLoad() { 
    super.viewDidLoad() 

    Timer.scheduledTimer(
     timeInterval: 5.0, 
     target:self.notificationView, 
     selector: #selector(NotificationView.timerFired(_:)), 
     userInfo: nil, 
     repeats: false 
    ) 

    } 
} 
0

下記のコードは私のために働いた(遊び場/スウィフト3で):

class SomeClass { 

    @objc public func timerFired(_ timer: Timer) { 
     print("Timer Fired") 
    } 
} 

let s = SomeClass() 

Timer.scheduledTimer(timeInterval: 5.0, target:s, selector: #selector(s.timerFired(_:)), userInfo: nil, repeats: false).fire() 
//This also will work 
//Timer.scheduledTimer(timeInterval: 5.0, target:s, selector: #selector(SomeClass.timerFired(_:)), userInfo: nil, repeats: false).fire() 
関連する問題