2016-02-17 56 views
1

我有这样的代码:Swift选择器到协议功能?

protocol FooP { 
    ... 
} 

extension FooP { 
    func doFoo() { 
     print("foo") 
    } 
    func doFoo(timer: NSTimer) { 
     doFoo() 
    } 
} 
class A : NSObject, UITableViewDataSource, FooP { 
    var timer : NSTimer? 

    ... 

    func startUpdating() { 
     timer = NSTimer.scheduledTimerWithTimeInterval(
     1.0, 
     target: self, 
     selector: Selector("doFoo:"), 
     userInfo: nil, 
     repeats: true 
    ) 
    } 
} 

不幸的是它崩溃的时候,我开始计时程序崩溃与

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[xyz.A doFoo:]: unrecognized selector sent to instance 0x7fb2041c4ac0' 

我怎样才能使它发挥作用(我想保持内部协议实现doFoo的) ?

如果我将doFoo移入A类定义一切正常,但正如我所说我想在协议内部实现此功能。

换句话说,我需要选择,说

"Hey I point to function named "doFoo" that is implemented as extension to FooP" 

现在选择似乎是说

"Hey I point to function named "doFoo" that is implemented in A class" 
+0

可能重复的[“无法识别的选择器发送到实例”在Swift](http://stackoverflow.com/questions/24094620/unrecognized-selector-sent-to-instance-in-swift) – Matheno

+0

不是我的问题是,计时器看不到功能作为协议 – Pikacz

+0

的扩展实现我有同样的问题。你有没有解决方案?我现在只是在我的班级实施功能 –

回答

1

尽量在操场上玩耍。你的麻烦是,在协议扩展中不可能定义@objc func。因此,请参阅可能的解决方法

import XCPlayground 
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true 
import Foundation 

protocol FooP { 
} 

extension FooP { 
    func doFoo() { 
     print("foo") 
    } 
    func doFoo(timer: NSTimer) { 
     print("dofoo") 
     doFoo() 
    } 
} 
class A: FooP { 
    var timer : NSTimer? 
    @objc func foo(timer: NSTimer) { 
     doFoo(timer) 
    } 
    func startUpdating() { 
     timer = NSTimer.scheduledTimerWithTimeInterval(
      1.0, 
      target: self, 
      selector: "foo:", 
      userInfo: nil, 
      repeats: true 
     ) 
    } 
} 

let a = A() 
a.startUpdating() 

如果您在类A中移动doFoo,为什么它适合您?那是因为你的类继承自NSObject,所以@objc关键字不是必需的。

1

问题是,NSTimer和整个Selector()业务都是Objective-C的东西,并且由于桥接而在Swift域中工作。然而,斯威夫特的默认协议实现是而不是桥接到Objective-C仙境(还),这就是为什么你的计时器失败。基本上,从Objective-C透视对象类型A不是对选择器doFoo:,句点作出响应。

因此,为长期解决方案报告此用例以快速进化。短期的,使用某种解决方法。

顺便说一句,你可能会觉得它有趣的阅读(甚至参与)在这thread