2016-02-17 55 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