我有一个问题,如果我将它作为委托(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/