代表-Class 从未发布

Delegate-Class Never Released

我有问题,如果我将它作为委托传递给 NSURLSession:

,我的委托-class 永远不会重新初始化
// 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 作为委托,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 完成会话时,您需要在 self.session 上调用这两种方法之一。