var searchDelayer:NSTimer?
func searchBar(searchBar: UISearchBar!, textDidChange searchText: String!) {
searchDelayer?.invalidate()
searchDelayer = nil
searchDelayer = NSTimer.scheduledTimerWithTimeInterval(1.5, target: self, selector: Selector("doDelayedSearch:"), userInfo: searchText, repeats: false)
}
func doDelayedSearch(text:String){
...
}
为什么此代码崩溃并显示错误消息:
[__NSCFTimer copyWithZone:]: unrecognized selector sent to instance
Updated:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFTimer copyWithZone:]: unrecognized selector sent to instance 0x7f9c622ae7e0'
*** First throw call stack:
(
0 CoreFoundation 0x000000010c05b3e5 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010ba42967 objc_exception_throw + 45
2 CoreFoundation 0x000000010c0624fd -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x000000010bfba7ec ___forwarding___ + 988
4 CoreFoundation 0x000000010bfba388 _CF_forwarding_prep_0 + 120
5 CoreFoundation 0x000000010bf32935 CFStringCreateCopy + 229
6 libswiftFoundation.dylib 0x000000010dc41314 _TF10Foundation24_convertNSStringToStringFCSo8NSStringSS + 116
7 MapCode 0x000000010a1a567e _TToFC7MapCode17MapViewController15doDelayedSearchfS0_FSST_ + 62
8 Foundation 0x000000010b5fce94 __NSFireTimer + 83
9 CoreFoundation 0x000000010bfc34d4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
10 CoreFoundation 0x000000010bfc3095 __CFRunLoopDoTimer + 1045
11 CoreFoundation 0x000000010bf863cd __CFRunLoopRun + 1901
12 CoreFoundation 0x000000010bf859f6 CFRunLoopRunSpecific + 470
13 GraphicsServices 0x000000010ecfd9f0 GSEventRunModal + 161
14 UIKit 0x000000010c96b990 UIApplicationMain + 1282
15 MapCode 0x000000010a1b3fee top_level_code + 78
16 MapCode 0x000000010a1b402a main + 42
17 libdyld.dylib 0x000000010f9d7145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
计时器回调函数必须是不带参数的函数,或者
一个函数取一个NSTimer
作为单个参数。
在你的情况下,它应该是
func doDelayedSearch(timer: NSTimer) {
let searchText = timer.userInfo as String
// ...
}
旧答案:(以下说法正确,但不适用于此处)
定时器的目标(self
在你的情况下)需要与 Objective-C 兼容,
即源自NSObject
或标有@objc
.
也可以看看在 Objective-C 中公开 Swift 接口 https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html在里面
“使用 Swift 与 Cocoa 和 Objective-C”文档(重点是我的):
The @objc
属性使您的 Swift API 在 Objective-C 中可用,并且
Objective-C 运行时。换句话说,您可以使用@objc
任何 Swift 方法、属性、下标、初始化器之前的属性,
或您想要从 Objective-C 代码使用的类。如果你的班级
继承自 Objective-C 类,编译器插入属性
为你。
...
当您使用时,此属性也很有用
Objective-C 类使用选择器来实现目标操作设计模式 - 例如,NSTimer
or UIButton
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)