2016-02-26 47 views
0

我試圖用NSTimer實現一個函數,但功能與下面的錯誤消息hollet。終止應用程序由於在NSTimer使用上未捕獲的異常'NSInvalidArgumentException'

我的代碼: 進口SpriteKit

class GameScene: SKScene { 
    override func didMoveToView(view: SKView) { 
    } 

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { 

    let userInfo:String = "Hello" 
     NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "helloWorld", userInfo: userInfo, repeats: false) 
    } 

    func helloWorld(timer: NSTimer) { 

     guard let userInfo = timer.userInfo as? String else { 
      fatalError() 
     } 

     let myLabel = SKLabelNode(fontNamed:"Chalkduster") 
     myLabel.text = userInfo 
     myLabel.fontSize = 45 
     myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)) 

     self.addChild(myLabel) 
    } 
} 

而且我得到了下面的錯誤。

sampleProgram[50257:2466422] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[sampleProgram.GameScene helloWorld]: unrecognized selector sent to instance 0x7fa168ec0770' 
*** First throw call stack: 
(
    0 CoreFoundation      0x0000000109548e65 __exceptionPreprocess + 165 
    1 libobjc.A.dylib      0x000000010b68ddeb objc_exception_throw + 48 
    2 CoreFoundation      0x000000010955148d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205 
    3 CoreFoundation      0x000000010949e90a ___forwarding___ + 970 
    4 CoreFoundation      0x000000010949e4b8 _CF_forwarding_prep_0 + 120 
    5 Foundation       0x0000000109b560d1 __NSFireTimer + 83 
    6 CoreFoundation      0x00000001094a8c84 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20 
    7 CoreFoundation      0x00000001094a8831 __CFRunLoopDoTimer + 1089 
    8 CoreFoundation      0x000000010946a241 __CFRunLoopRun + 1937 
    9 CoreFoundation      0x0000000109469828 CFRunLoopRunSpecific + 488 
    10 GraphicsServices     0x000000010f7c2ad2 GSEventRunModal + 161 
    11 UIKit        0x000000010a16a610 UIApplicationMain + 171 
    12 sampleProgram      0x00000001093681fd main + 109 
    13 libdyld.dylib      0x000000010c20592d start + 1 
) 
libc++abi.dylib: terminating with uncaught exception of type NSException (lldb) 

我真的很感激,如果有人讓我知道這個錯誤或解決方法的原因。

回答

0

您的操作需要一個參數,因此當您將其傳遞給定時器時,必須將選擇器稱爲"helloWorld:"(注意末尾的:)。

+0

非常感謝!我沒想到我可以簡單地解決這個問題。 – vanagar

相關問題