3 ms·
I find it extremely dangerous if issues arise rarely but not rarely enough stop thinking about them and not as rarely as you would think. Look at this terrifyin
by fauigerzigerk 8y ago
I find it extremely dangerous if issues arise rarely but not rarely enough stop thinking about them and not as rarely as you would think. Look at this terrifying example from [1]. How long do you have to look at this code to tell if there is a reference cycle or not?
class ServiceLayer {
// ...
private var task: URLSessionDataTask?
func foo(url: URL) {
task = URLSession.shared.dataTask(with: url) { data, response, error in
let result = // process data
DispatchQueue.main.async { [weak self] in
self?.handleResult(result)
}
}
task?.resume()
}
deinit {
task?.cancel()
}
}
[1] http://marksands.github.io/2018/05/15/an-exhaustive-look-at-memory-management-in-swift.html http://marksands.github.io/2018/05/15/an-exhaustive-look-at-...
- saagarjha 8y agoI think the "catch" is that dataTask will retain self? Yeah, I agree that capture semantics with closures is a bit complicated to get right.
- fauigerzigerk 8y agoYes, dataTask will retain self in spite of the fact that [weak self] is used in the only place where self is explicitly referenced. This is baffling. After reading the linked article I have come to think that reference counting is not a good fit for a language that mixes object orientation with functional idioms including tons of closures.