1

I'm trying to implement a pure swift class. One of the class methods needs to be called every 60 seconds. In Objective-C I would use an NSTimer, however I want this to be pure Swift if I can without having an NSObject subclass.

So I'm thinking of doing something like this:

func autoDelete() {
     .... code here

    // call myself in 60 seconds
    delay(60, { () -> () in
        self.autoDelete()
    })
}

func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

My concern is that because this is sort of a recursive call it will eventually overflow the stack. Would this happen? What are my alternatives? Is subclassing NSObject and use an NSTimer my only viable option?

Aaron Bratcher
  • 6,051
  • 2
  • 39
  • 70

1 Answers1

1

Your code does not cause a stack overflow, because dispatch_after() only dispatches the block for later execution and then returns.

A possible disadvantage of your solution is that it starts a new timer every 60 seconds. Timers are not 100% precise, so small differences could accumulate.

A better solution (if you want to avoid NSTimer) would be to use a dispatch timer, as described in this answer to Do something every x minutes in Swift.

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382