在 Swift 中使用 NSTimer 查找选择器时出错
Error finding selector using NSTimer in Swift
我正在尝试使用 NSTimer 函数每五秒检查一次请求。除了我收到错误:
MyApp[13952:2483629] *** NSForwarding: warning: object 0x7f98cd15ab80 of class 'MyApp.Requests' does not implement methodSignatureForSelector: -- trouble ahead
Unrecognized selector -[MyApp.Requests checkReq:]
我的代码简化如下:
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)
}
}
请注意,我查看了本网站上针对相同错误的其他答案,发现它们都是非常过时的答案。这是 XCode 6.4 和 Swift 1.2。 Objective-C 这里不涉及。
我也试过使用 Selector("checkReq:") 没有用。
你的class(必须是class,不是结构或枚举)这个代码所属的必须继承自NSObject
.
更严格地说,无论您在 NSTimer.scheduledTimerWithTimeInterval
的 target:
参数中输入哪个 class,都必须继承自 NSObject
。在这种情况下,它恰好是self
在另一种情况下,它可能不是。
Cocoa的目标选择器模式需要符合 NSObject 协议。
使您的 class 成为 NSObject
的子class
我正在尝试使用 NSTimer 函数每五秒检查一次请求。除了我收到错误:
MyApp[13952:2483629] *** NSForwarding: warning: object 0x7f98cd15ab80 of class 'MyApp.Requests' does not implement methodSignatureForSelector: -- trouble ahead
Unrecognized selector -[MyApp.Requests checkReq:]
我的代码简化如下:
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)
}
}
请注意,我查看了本网站上针对相同错误的其他答案,发现它们都是非常过时的答案。这是 XCode 6.4 和 Swift 1.2。 Objective-C 这里不涉及。
我也试过使用 Selector("checkReq:") 没有用。
你的class(必须是class,不是结构或枚举)这个代码所属的必须继承自NSObject
.
更严格地说,无论您在 NSTimer.scheduledTimerWithTimeInterval
的 target:
参数中输入哪个 class,都必须继承自 NSObject
。在这种情况下,它恰好是self
在另一种情况下,它可能不是。
Cocoa的目标选择器模式需要符合 NSObject 协议。
使您的 class 成为 NSObject
的子class