Memory leak when using NSURLSession.downloadTaskWithURL

后端 未结 4 2030
猫巷女王i
猫巷女王i 2020-12-02 21:43

So I hit another roadblock in my endeavors with Swift. I am trying to load multiple images into an image gallery - all works fine except of one thing. The memory use of the

4条回答
  •  失恋的感觉
    2020-12-02 22:08

    After URLSession resumes its data task ,If you no longer need a session, you can invalidate it by calling either invalidateAndCancel() (to cancel outstanding tasks) or finishTasksAndInvalidate() (to allow outstanding tasks to finish before invalidating the object). i think you are not invalidating the URLSession.So here memory leaks happen so you need to add any one of those above function and check in instruments in memory leaks sections .and your modified function will be like this

    func loadImageWithIndex(index: Int) {
        let imageURL = promotions[index].imageURL
        let url = NSURL(string: imageURL)!
        let urlSession = NSURLSession.sharedSession()
        let query = urlSession.downloadTaskWithURL(url, completionHandler: { location, response, error -> Void in
    
        })
        query.resume()
        query.finishTasksAndInvalidate()
    }
    

提交回复
热议问题