Created
April 1, 2020 14:42
-
-
Save mfaani/639c8ebd8b613c45cb07070f6f7c8b29 to your computer and use it in GitHub Desktop.
Related to https://stackoverflow.com/a/38372384/5175709 Trying to show setting `item` to `nil` doesn't seem to be necessary
This file contains hidden or 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 | |
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 | |
*/ |
This file contains hidden or 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 | |
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 | |
} | |
queue.async(execute: item!) | |
queue.asyncAfter(deadline: .now() + 5) { | |
item?.cancel() | |
item = nil | |
} | |
} | |
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: | |
0 | |
0 | |
1 | |
1 | |
deallocated | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What about the following example, I'm trying to cancel previously running work items (if there had been any). I'm unable to avoid a leak when not running the operation at all (i.e. Cancel immediately). Likely I'm too focussed on this now.
Edit:
Looks like it's the Work Item inside testDispatchItems which leaks. That one must be nilled.Still leaking at least once.