2017-12-29 26 views
2

アプリが開いていてもバックグラウンドで実行されていても、5秒ごとに呼び出すメソッドを取得しようとしています。そのため、AppDelegateでは、 5秒ごとにメソッドを呼び出して、タイマーを持っています。AppDelegateでインスタンスに送信されたセレクタが認識されない

var helloWorldTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(sayHello), userInfo: nil, repeats: true) 

@objc func sayHello() 
{ 
    print("hello World") 
} 

はしかし、私はこのエラーを取得する:

NSInvalidArgumentException', reason: '-[_SwiftValue sayHello]: unrecognized selector sent to instance 

そしてメソッドが正しく参照されているので、私は、なぜ完全にわからないんだけど?なぜこのエラーが出るのか誰にも分かりますか?

答えて

4

AppDelegateが完全に初期化される前にselfを使用できないため、クラッシュしています(target: self)。ですから、このようにタイマーを初期化する必要があります。

Setting a Default Property Value with a Closure or Functionから、アップルのマニュアルを引用
var helloWorldTimer:Timer? 

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
    self.helloWorldTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(sayHello), userInfo: nil, repeats: true) 
    return true 
} 

さらに

If you use a closure to initialize a property, remember that the rest of the instance has not yet been initialized at the point that the closure is executed. This means that you cannot access any other property values from within your closure, even if those properties have default values.

You also cannot use the implicit self property, or call any of the instance’s methods.

関連する問題