This will result in a memory leak using the quick class method.

My problem: I'm not sure if closing inside a class method can lead to a memory leak. Here is my code

class func SomeDownloadFun (pdfDirectory:String) { let destination : DownloadRequest.DownloadFileDestination = { _, response in //----------HERE I Reference the item 'pdfDirectory'-----Will this cause leak? let fileURL = URL(fileURLWithPath: pdfDirectory) return (fileURL,[.removePreviousFile,.createIntermediateDirectories]) } let downLoadRequest = Alamofire.download(urlStr!, to: destination) downLoadRequest.responseData(completionHandler: { (response) in switch response.result { case .success: //----------HERE I Reference the item 'pdfDirectory'-----Will this cause leak? print("pdfDirectory") break case .failure: print("down err") break } }) 

}

Aa I have a comment where I think it will leak, can someone tell me, thanks! 🙏

+5
source share
1 answer

A few observations:

  • Just because you reference the object in closure does not mean that you have a strong reference cycle. You need circular links (for example, A has a strong link to B and B, has its own strong link to A) in order to have a strong reference loop that does not occur here.

  • pdfDirectory not even a reference type ( String is a struct , a value type), so there can be no strong reference loop in any case. Its the only thing that will happen with reference types (e.g. class , not struct ).

Even if you introduced NSDictionary into conversation (type reference), that in itself is not enough to have a strong loop reference. Do not go to conclusions about strong reference loops based on the existence of a closure with some reference type. Print (or use the "Memory Debugging Schedule" or "Tools") which objects to which the given object has strong links, and see if there is a strong link cycle in this place.

0
source

Source: https://habr.com/ru/post/1268691/


All Articles