I'm new to swift

Now I work with Dispatch and there is a situation when I need to go back to the main thread and I use clouser . So clouser keeps the object with a strong link in order to properly handle such a situation make capturing .

The question is what I am working on now with an example in which capturing does not look like this

 private func fetchData() { if let url = imageURL { Dispatch.__dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0).async { let contentData = NSData(contentsOf: url as URL) DispatchQueue.main.async { if url == self.imageURL { if let imageData = contentData { self.image = UIImage(data: imageData as Data) } } else { print("ignored data returned from \(url)") } } } } } 

An example explains a smart developer, so I think that he specifically missed this capturing , but I do not understand why ...

I think it should be written like this

 private func fetchData() { if let url = imageURL { Dispatch.__dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.rawValue), 0).async { let contentData = NSData(contentsOf: url as URL) DispatchQueue.main.async { [weak weakSelf = self] in if url == weakSelf!.imageURL { if let imageData = contentData { weakSelf!.image = UIImage(data: imageData as Data) } } else { print("ignored data returned from \(url)") } } } 

So now it is not clear in which situation capturing to be written, and in which there is not

    1 answer 1

    There are 2 types of closures :

    • escaping
    • non-escaping

    In the case of c non-escaping closures no need to worry about memory leaks, since they cannot be there, they are already worried about us.

    But in the case of escaping closures really can capture a strong link and get a memory leak. Here we need to worry and use weak or unowned .

    How to define escaping or non-escaping ? Well, for example read the description:

    enter image description here

    How best to write it already in their own way. For example, my version of the record in your case will be:

     DispatchQueue.main.async { [weak self] in if let wSelf = self { ... } }