Swift self in a class [已关闭]

4xrmg8kj  于 2023-06-04  发布在  Swift
关注(0)|答案(1)|浏览(128)

**关闭。**此题需要debugging details。目前不接受答复。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答这个问题。
昨天关门了。
Improve this question


为什么我不能在这里使用self?所有这些都在类MyTimer,所以我不明白为什么它给我这个错误.
我想要一个定时器,其中scheduledTimer属于MyTimer类的每个示例。我不能把目标设定为自己。

icomxhvb

icomxhvb1#

出现此问题是因为您试图在MyTimer对象本身的init中创建Timer。此时,self对象尚未完全初始化,因此不能将其用作Timer的目标。只有在init方法完成执行后,self才可以完全访问。
为了克服这个问题,您可以将theTimerThing声明为MyTimer类的可选存储属性,并在初始化self的所有其他属性之后,在init方法中示例化它。这允许您将self作为目标传递给Timer。
请注意,theTimerThing必须是可选的,因为在self完全初始化之前,它不能被赋非nil值。一旦self准备好了,您就可以示例化Timer并将其分配给theTimerThing。
下面是更正后的代码片段:

class MyTimer: Hashable {
    var name: String = ""
    var hour: Int = 0
    var min: Int = 0
    var status: CountDownState
    var timer: Timer?
    var theTimerThing: Timer?
    
    init(name: String, hour: Int, min: Int, status: CountDownState) {
        self.name = name
        self.hour = hour
        self.min = min
        self.status = status
        
        theTimerThing = Timer.scheduledTimer(
            timeInterval: 1.0,
            target: self,
            selector: #selector(fire),
            userInfo: nil,
            repeats: true)
    }
    ...

相关问题