Memory Leak on scaling image in iOS using SWIFT
<p>I have an app that displays images and scales them to certain size.
Here is the code for the scaling:</p>

<pre><code>static func scaledImage(originalImage image: UIImage, scaledToSize size: CGSize) -&gt; UIImage {        
    UIGraphicsBeginImageContextWithOptions(size, true, 0.0)
    image.drawInRect(CGRectMake(0, 0, size.width, size.height))
    let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return scaledImage
}
</code></pre>

<p>and here is how the call to the function is being made:</p>

<pre><code>for i in 0 ..&lt; images.count{
    if let data = images[i].imageData, let originalImage = UIImage(data: data) {
        previewImage = scaledImage(originalImage: originalImage, scaledToSize: desiredSize)            
    } 
} 
</code></pre>

<p>The app was crashing for 50 images 
When i used instruments to find where the memory was allocated it told me that this line allocates 960 MB:
image.drawInRect(CGRectMake(0, 0, size.width, size.height))</p>

<p>and that is quite a lot of memory.</p>

<p>So my question is what is being done wrong here?
How to solve that memory leak.</p>

<p>I searched through lots of examples on how to scale images but they were more or less the same. There was no example on memory management and due to the fact that i do not have lots of experience in image processing i have no idea how to approach this problem.</p>

<p>Any help here will be much appreciated.
Thanks in advance </p>