Search code examples
iosswiftnstimerxcode6.4

Error finding selector using NSTimer in Swift


I am trying to use the NSTimer function to check on a request every five seconds. Except I am getting the error:

MyApp[13952:2483629] *** NSForwarding: warning: object 0x7f98cd15ab80 of class 'MyApp.Requests' does not implement methodSignatureForSelector: -- trouble ahead

Unrecognized selector -[MyApp.Requests checkReq:]

My code is simplified below:

var timer: NSTimer?

    func parseUberRequest(dict: NSDictionary) {
        if let reqId = dict["request_id"] as? String {
            timer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: "checkReq:", userInfo: ["reqId" : reqId], repeats: false)
        }
    }

    func checkReq(timer: NSTimer) {
        let userInfo = timer.userInfo as! Dictionary<String, String>
        if let reqId = userInfo["reqId"] {
            println(reqId)
        }

    }

Please know that I have looked at other answers for the same error on this site and have found them to all be incredibly outdated answers. This is XCode 6.4 and Swift 1.2. Objective-C is NOT involved here.

I also tried using Selector("checkReq:") to no avail.


Solution

  • Your class (it must be a class, not a struct or an enum) that this code belongs to must inherit from NSObject.

    More strictly speaking whichever class you put in the target: parameter of NSTimer.scheduledTimerWithTimeInterval must inherit from NSObject. In this case, it happens to be self in another case, it may not be.