Initializing Swift properties that require “self” as an argument

后端 未结 3 676
一向
一向 2020-12-11 02:45

I have a Swift class that I\'d like to look something like this:

class UpdateManager {
  let timer: NSTimer

  init() {
    timer = NSTimer(timeInterval: 600         


        
3条回答
  •  清歌不尽
    2020-12-11 03:39

    Aside from the implicitly unwrapped optional, I found that to get the code working I needed to subclass NSObject and to also add the timer to current run loop.

    class UpdateManager:NSObject {
        let timer: NSTimer!
    
        override init() {
            super.init()
            timer = NSTimer(timeInterval: 600, target: self, selector: "check", userInfo: nil, repeats: true)
            NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
        }
    
    
        func check() {
            // Do some stuff
    
        }
    }
    

    Updated code based on comments - thank you to jtbandes and Caroline

    class UpdateManager {
        let timer: NSTimer!
    
       init() {
    
            timer = NSTimer.scheduledTimerWithTimeInterval(600,
                target: self,
                selector: "check",
                userInfo: nil,
                repeats: true)
        }
    
    
       @objc func check() {
            // Do some stuff
    
        }
    }
    

提交回复
热议问题