Skip to content

Instantly share code, notes, and snippets.

@maxsz
Last active October 26, 2018 11:21
Show Gist options
  • Save maxsz/47986a233d1fc400dd29 to your computer and use it in GitHub Desktop.
Save maxsz/47986a233d1fc400dd29 to your computer and use it in GitHub Desktop.
Delayed NSOperation
class DelayedBlockOperation: NSOperation {
private var delay: NSTimeInterval = 0
private var block: (() -> Void)? = nil
private var queue: dispatch_queue_t = dispatch_get_main_queue()
override var asynchronous: Bool { return true }
override var executing : Bool {
get { return _executing }
set {
willChangeValueForKey("isExecuting")
_executing = newValue
didChangeValueForKey("isExecuting")
}
}
private var _executing : Bool = false
override var finished : Bool {
get { return _finished }
set {
willChangeValueForKey("isFinished")
_finished = newValue
didChangeValueForKey("isFinished")
}
}
private var _finished : Bool = false
init(delay: NSTimeInterval, _ block: () -> Void) {
self.delay = delay
self.block = block
}
init(delay: NSTimeInterval, queue: dispatch_queue_t, _ block: () -> Void) {
self.delay = delay
self.queue = queue
self.block = block
}
override func start() {
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(delay) * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, queue) {
guard !self.cancelled else {
self.finished = true
return
}
guard let block = self.block else {
self.finished = true
return
}
self.executing = true
block()
self.finished = true
}
}
}
// Usage:
// let op = DelayedBlockOperation(delay: 10) {
// print("Executing operation")
// }
// NSOperationQueue().addOperation(op)
// If you cancel the operation with `op.cancel()` before the
// delay, the block is not executed :)
@acalism
Copy link

acalism commented Sep 20, 2018

Swift 2.x?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment