Memory leak when using NSURLSession.downloadTaskWithURL

后端 未结 4 2044
猫巷女王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:21

    I faced a similar issue in a recent app.

    In my situation I was downloading a number of images from an API. For each image I was creating an NSURLSessionDownloadTask and adding it to a NSURLSession with an ephemeral configuration. When the task was complete I called a completion block to process the downloaded data.

    Each download task that I added caused additional memory to be allocated (according to the Xcode debugger) that was not released at any point thereafter. When downloading approximately 100 images, the debugger had the memory usage as ~600 MB. The more download tasks, the more memory, that was allocated and not released. At no point had I displayed or used the image data in any way, it was simply stored to disk.

    Trying to diagnose the issue in instruments was not fruitful. Instruments showed no leaks, and no allocations corresponding to the download tasks or image data. There were no memory leaks due to retain cycles in my blocks or the like, only in the debugger did the memory spiral.

    After several hours of trial and error including:

    • Downloading the images with the completion block set to nil (to ensure I did not have a retain cycle in the block).

    • Commenting out various parts of my code to make sure that the allocations occurred precisely when '[downloadTask resume]' was called.

    • Setting the URLCache for the session to both nil and a cache with a size of 0. As per: http://www.drdobbs.com/architecture-and-design/memory-leaks-in-ios-7/240168600

    • Changing the NSURLSession configuration to the default configuration.

    Finally I switched my NSURLSession configuration from an ephemeral type to a background type. This required that I not use a completion block to process the images. I instead processed them in the delegate. This solved the issue for me. Adding download tasks to the background NSURLSession resulted in almost zero memory growth as the downloads were initiated and processed.

    I wish I had a better understanding of why this is the case, but I unfortunately do not. I have seen this issue crop up for others as well and have yet to come across a better solution or explanation.

提交回复
热议问题