2017-12-29 10 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). 그래서 당신은이 방법으로 타이머를 초기화해야합니다


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 
} 
Setting a Default Property Value with a Closure or Function에서 애플 설명서를 인용 :

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.

관련 문제