Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will it cause memory leak with in a swift class method

My problem is I'm not sure if a closure inside a class method can leads to 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 comment out where i think it will cause a leak ,can anybody tell me ,Thanks!🙏

like image 382
Tek.ke Avatar asked Oct 30 '22 06:10

Tek.ke


1 Answers

A couple of observations:

  1. Just because you reference an object in a closure doesn’t mean you have a strong reference cycle. You need circular references (e.g. A has strong reference to B and B has its own strong reference back to A), in order to have strong reference cycle, which doesn’t happen here.

  2. The pdfDirectory isn’t even a reference type (String is a struct, a value type), so there can’t be a strong reference cycle, anyway. It’s only going to happen with reference types (e.g. class rather than struct).

Even when you introduced NSDictionary into the conversation (a reference type), that alone is not sufficient for there to be a strong reference cycle. Don't jump to conclusions about strong reference cycles on the basis of the existence of closure with some reference type. Figure out (or use "Debug memory graph" or Instruments) what objects to which a given object has strong references, and see determine if there are strong reference cycle at that point.

like image 163
Rob Avatar answered Nov 15 '22 05:11

Rob