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

时间:2016-02-26 00:36:57

标签: ios swift sprite-kit

我正在尝试使用NSTimer实现一个函数,但该函数会出现以下错误消息。

我的代码:     导入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) 

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

1 个答案:

答案 0 :(得分:0)

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