Search code examples
swiftselectornstimer

Swift - Method exist,But the error:unrecognized selector sent to instance


class MCPoll: NSObject {

    private var pollTimer: NSTimer!

    func startPoll(){
        pollTimer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("poll"), userInfo: nil, repeats: false)
    }

    private func poll(){ }
}

"poll" is a no-argument function, but xcode tips:

2015-03-24 11:08:20.478 mobile[7897:1138436] -[mobile.MCPoll poll]: unrecognized selector sent to instance 0x174276940

Other classes in my project is using "NSTimer",But no problems.

this crash log:

Last Exception Backtrace: 
0   CoreFoundation       0x186e96530 __exceptionPreprocess + 132
1   libobjc.A.dylib      0x197e6c0e4 objc_exception_throw + 60
2   CoreFoundation       0x186e9d5f4 -[NSObject(NSObject) doesNotRecognizeSelector:] + 220 
3   CoreFoundation       0x186e9a3ac ___forwarding___ + 928 
4   CoreFoundation       0x186d9ec4c _CF_forwarding_prep_0 + 92
5   Foundation           0x187d8f514 __NSFireTimer + 92 
6   CoreFoundation       0x186e4ec20  __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 28 
7   CoreFoundation       0x186e4e8d0 __CFRunLoopDoTimer + 888 
8   CoreFoundation       0x186e4c31c __CFRunLoopRun + 1372 
9   CoreFoundation       0x186d791f4 CFRunLoopRunSpecific + 396
10  GraphicsServices     0x19019b6fc GSEventRunModal + 168
11  UIKit                0x18b70a10c UIApplicationMain + 1488 
12  MeChat               0x1001016dc top_level_code (AppDelegate.swift:0) 
13  MeChat               0x10010171c main (AppDelegate.swift:0) 
14  libdyld.dylib        0x1984eaa08 start + 4

Solution

  • If you want to keep the function private instead of exposing it as public or internal, you can also add the @objc attribute. This attribute exposes the method to the Objective-C runtime. So your method declaration would be

    @objc private func poll(){ }