类 Y 的对象 X 未在 Swift 中实现 methodSignatureForSelector [英] Object X of class Y does not implement methodSignatureForSelector in Swift

查看:29
本文介绍了类 Y 的对象 X 未在 Swift 中实现 methodSignatureForSelector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Person 类,它被多次实例化.每个人都有自己的计时器.在 Personinit 中,我调用 startTimer().

I have a class Person which is instantiated multiple times.Each person get's their own timer. Upon in my init for Person I call 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)")
 }
...
...
}

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

So I may have 3 instances of Person in an array of Person[]. I am getting an error:

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 中.该函数在类中,所以我不知道该怎么做.

I read elsewhere that I should inherit from NSObject but this is in Swift not Obj-C. The function is within the class so I am not sure what to do.

推荐答案

不要把 NSObject 看作一个 Objective-C 类,把它看作一个 Cocoa/Foundation 类.即使您使用的是 Swift 而不是 Objective-C,您仍在使用所有相同的框架.

Don't think of NSObject as an Objective-C class, think of it as a Cocoa/Foundation class. Even though you're using Swift instead of Objective-C, you're still using all the same frameworks.

两个选项:(1)将dynamic属性添加到要作为选择器引用的函数中:

Two options: (1) add the dynamic attribute to the function you want to reference as a selector:

    dynamic func timerTick() {
        self.angerLevel++
        print("Angry! \(self.angerLevel)")
    }

或 (2) 将 Person 声明为 NSObject 的子类,然后在初始化程序的开头调用 super.init():

Or (2) declare Person as a subclass of NSObject, then just call super.init() at the beginning of your initializer:

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()
    }
}

这篇关于类 Y 的对象 X 未在 Swift 中实现 methodSignatureForSelector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆