swift - 委托(delegate)类从未发布

标签 swift memory-management memory-leaks retain-cycle

我有一个问题,如果我将它作为委托(delegate)传递给 NSURLSession,我的委托(delegate)类永远不会重新初始化:

// Playground-compatible
import Foundation

class Downloader: NSObject, URLSessionDataDelegate {
    private var session: URLSession! = nil
    private var dataTask: URLSessionDataTask! = nil

    init(url: URL) {
        super.init()
        let request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 60)
        self.session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
        self.dataTask = session.dataTask(with: request)
    }

    deinit {
        print("Downloader released")
    }

    func dummy() -> String {
        self.dataTask = nil // I've also tried it without this
        self.session = nil  // I've also tried it without this
        return "Dummy 👨🏻‍🎤"
    }
}
func test() {
    let downloader = Downloader(url: URL(fileURLWithPath: "/"))
    print(downloader.dummy())
}

test()
print("After test")

如果我传递 nil 而不是 self 作为委托(delegate),Downloader 将被取消初始化;但显然这不是解决方案^^

最佳答案

请阅读URLSession init(configuration:delegate:delegateQueue:)的文档和delegate参数的说明:

Important

The session object keeps a strong reference to the delegate until your app exits or explicitly invalidates the session. If you do not invalidate the session by calling the invalidateAndCancel() or finishTasksAndInvalidate() method, your app leaks memory until it exits.

当您的Downloader 完成 session 时,您需要在self.session 上调用这两个方法之一。

关于swift - 委托(delegate)类从未发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49257382/

相关文章:

ios - 导航栏在运行时改变颜色

ios - 设置WKWebView scrollView的contentInset导致页面跳转到顶部

ios - 使用 MBProgressHUD 时的内存泄漏

delphi - FastMM4,如何读取日志文件?

ios - 快速比较两个数组并删除具有不匹配的特定字段的元素

c - 以下代码是否泄漏内存

swift - 在一个类中引用一个类的实例数组会产生强引用循环吗?

C++,为什么在修改新分配的对象后会出现访问冲突?

在线程内部调用时,Python 队列内存泄漏

swift - MKOverlay 自定义描边 - CGPath