终止应用程序由于在NSTimer使用上未捕获的异常'NSInvalidArgumentException'

问题描述:

我试图用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) 

我真的很感激,如果有人让我知道这个错误或解决方法的原因。

您的操作需要一个参数,因此当您将其传递给定时器时,必须将选择器称为"helloWorld:"(注意末尾的:)。

+0

非常感谢!我没想到我可以简单地解决这个问题。 – vanagar