类Y的对象X在Swift中未实现methodSignatureForSelector

我有一个类Person被实例化多次。每个人都有自己的计时器。当我在init为Person我打电话startTimer()。


class Person {

 var timer = NSTimer()

 func startTimer() {

    timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("timerTick"), userInfo: nil, repeats: true)

 }


 func timerTick() {

    angerLevel++

    println("Angry! \(angerLevel)")

 }

...

...

}

所以我可能在的数组中有3个Person实例Person[]。我收到一个错误:


2014-06-25 13:57:14.956 ThisProgram[3842:148856] *** NSForwarding: warning: object 0x113760048 of class '_TtC11ThisProgram6Person' does not implement methodSignatureForSelector: -- trouble ahead

我在其他地方读过我应该继承的内容,NSObject但这是在Swift中而不是Obj-C中。该函数在该类中,因此我不确定该怎么做。


慕村9548890
浏览 823回答 3
3回答

HUX布斯

不要将其NSObject视为Objective-C类,而应将其视为可可/基础类。即使您使用Swift而不是Objective-C,您仍在使用所有相同的框架。两种选择:(1)将dynamic属性添加到要作为选择器引用的函数中:    dynamic func timerTick() {        self.angerLevel++        print("Angry! \(self.angerLevel)")    }或(2)声明Person为的子类NSObject,然后只需super.init()在初始化程序的开头进行调用:class Person: NSObject {    var timer = NSTimer()    var angerLevel = 0    func startTimer() {        print("starting timer")        timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "timerTick", userInfo: nil, repeats: true)    }    func timerTick() {        self.angerLevel++        print("Angry! \(self.angerLevel)")    }    override init() {        super.init()        self.startTimer()    }}

翻阅古今

我在尝试使用let encodedArchive = NSKeyedArchiver.archivedDataWithRootObject(archive) as NSData存档是自定义类的数组时遇到了类似的错误 。我发现将自定义类声明为NSObject和NSCoding的子类可以解决问题。它需要更多的行才能符合NSCoding的协议,因此,它看起来像这样:class Person: NSObject, NSCoding {  init() {    super.init()  }  func encodeWithCoder(_aCoder: NSCoder) {   }}

偶然的你

从XCode6 beta 6开始,您可以使用“动态”功能dynamic func timerTick() { .... }
打开App,查看更多内容
随时随地看视频慕课网APP