简体   繁体   English

它是否会在快速类方法中导致内存泄漏

[英]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!🙏 Aa我已经评论了我认为会导致泄漏的地方,任何人都可以告诉我,谢谢!🙏

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 (eg 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. 你需要循环引用(例如A有强引用B和B有自己的强引用回A),以便有强引用周期,这里不会发生。

  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. pdfDirectory甚至不是引用类型( Stringstruct ,值类型),因此无论如何都不能有强引用循环。 It's only going to happen with reference types (eg class rather than struct ). 它只会发生在引用类型(例如class而不是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. 即使您在对话中引入了NSDictionary (参考类型),仅仅这一点还不足以产生强大的参考周期。 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. 弄清楚(或使用“调试内存图”或“仪器”)给定对象具有强引用的对象,并查看在该点确定是否存在强引用循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM