I have this code, which runs a block of code after a delay.
public func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
The problem is that the view controller using the delay function persists even after dismissal. With the code removed, it becomes nil, as it should.
I need to know how to have a delay function, like this, but which wouldn't persist the object it was called from, and instead would just not call the block, in the event that it's otherwise no longer existent.
This is in Swift, but replies in Objective-C are entirely appreciated.
The problem, as others have pointed out, is that you are probably calling this function from the view controller, but have a reference to self
, which captures that view controller and keeps a strong reference to it.
So, let's say you did something like this from your view controller class:
delay(5) {
self.label.hidden = true
return
}
You would replace that with something that explicitly says that it should maintain weak
reference to self
:
delay(5) { [weak self] in
self?.label.hidden = true
return
}
Note, I had to unwrap the optional self
, when I used it. In this example, I used optional chaining to ensure this fails gracefully if self
is nil
by the time the closure is called.