Skip to content

Instantly share code, notes, and snippets.

@mfaani
Created April 1, 2020 14:37
Show Gist options
  • Save mfaani/5eb35438bc9b944bedaa22d37e989e48 to your computer and use it in GitHub Desktop.
Save mfaani/5eb35438bc9b944bedaa22d37e989e48 to your computer and use it in GitHub Desktop.
import Foundation
//Cancel without setting `item` to `nil`
class Foo {
func testDispatchItems() {
let queue = DispatchQueue.global()
var item: DispatchWorkItem?
item = DispatchWorkItem { [weak self] in
for i in 0 ... 10 {
if item?.isCancelled ?? true { break }
print(i)
self?.heavyWork(i)
}
// item = nil // resolve strong reference cycle
}
item?.cancel()
}
func heavyWork(_ num: Int) {
print(num)
}
deinit {
print("deallocated")
}
}
var c: Foo? = Foo()
c?.testDispatchItems()
c = nil
// no need to set item to `nil` when execution finishes...
/*
Output:
deallocated
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment