1

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.

Nathan McKaskle
  • 2,926
  • 12
  • 55
  • 93
  • Are these statements inside a class declaration? The code works in my test, Swift 2.0. – zaph Aug 29 '15 at 17:29
  • Comment on your edit... once you get everything else in place, the selector can be specified with either the Selector("checkReq:") or the "checkReq:" syntax. – mmc Aug 29 '15 at 17:42

2 Answers2

1

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.

mmc
  • 17,354
  • 2
  • 34
  • 52
  • I have another class that uses the timer, it doesn't inherit from NSObject. For some reason it works fine. It inherits from UIViewController and CLLLocationManagerDelegate. Do those inherit from NSObject? – Nathan McKaskle Aug 29 '15 at 18:20
  • UIViewController does. CLLLocationManagerDelegate is a protocol. – mmc Aug 30 '15 at 18:02
1

Cocoa's target-selector pattern needs to conform to the NSObject protocol.

Make your class a subclass of NSObject

vadian
  • 274,689
  • 30
  • 353
  • 361
  • I have a whole class where I did not have to do make it a subclass of NSObject, why did the timer I have in there work? I also don't have to do this for NSNotificationCenter. – Nathan McKaskle Aug 29 '15 at 17:29
  • See below, @vadian and I both misspoke. The class this code belongs to must inherit from NSObject *only* because you are sending self as the target object for the timer. The target has to inherit from NSObject, not necessarily the class that creates the NSTimer. – mmc Aug 29 '15 at 17:45
  • That other class uses self as the target too. I'm guessing the UIViewController inherits from NSObject? – Nathan McKaskle Aug 29 '15 at 18:22