Created
April 1, 2020 14:37
-
-
Save mfaani/5eb35438bc9b944bedaa22d37e989e48 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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