Swift - 方法存在,但错误 :unrecognized selector sent to instance

标签 swift selector nstimer

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”是一个无参函数,但是xcode提示:

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

我项目中的其他类正在使用“NSTimer”,但没有问题。

这个崩溃日志:

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

最佳答案

如果你想保持函数private而不是将其暴露为publicinternal,你也可以添加@ objc 属性。此属性将方法公开给 Objective-C 运行时。所以你的方法声明将是

@objc private func poll(){ }

关于Swift - 方法存在,但错误 :unrecognized selector sent to instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29224467/

相关文章:

swift - 生成敌人

ios - 在后台 IOS 7 上执行间隔输出

ios - 我是否必须快速删除内置观察者?

ios - 将 UIViewController 嵌入静态 UITableViewController 单元格中

ios - 当我在 View Controller 中移动时保存文本字段的值

Objective-C va_list 和选择器

ios - 图表实时更新图表 - 数据记录在一个 VC 上并绘制在另一个 VC 上

jQuery:选择器问题(图片)

swift - addTarget 和 addGestureRecognizer 之间的不同行为

ios - 自定义 tableViewCell 中的 NSTimer