I am trying to grasp how I can recognize when a strong retain cycle is possible and requires me to use [weak/unowned self]
. I've been burned by unnecessarily using [weak/unowned self]
and the self was deallocated immediately before giving me a chance to use it.
For example, below is an async network call that refers to self
in the closure. Can a memory leak happen here since the network call is made without storing the call it self into a variable?
NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) {
(data, response, error) in
self.data = data
)
Here's another example using the NSNotificationCenter, where a call can be made later asynchronously:
NSNotificationCenter.defaultCenter().addObserverForName(
UIApplicationSignificantTimeChangeNotification, object: nil, queue: nil) {
[unowned self] _ in
self.refresh()
}
My question is in what cases is a strong retain cycle possible? If I am making an asynchronous call or static call that references self in a closure, does that make it a candidate for [weak/unowned self]
? Thanks for shedding any light on this.