Swift UIGraphicsGetImageFromCurrentImageContext memory leaks

Viewed 1513

I have a centralized method to resize UIImages:

public extension UIImage {
    public func scaleToSize(size: CGSize) -> UIImage {
        let hasAlpha = true
        let scale: CGFloat = 0.0

        UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
        self.draw(in: CGRect(origin: CGPoint.zero, size: size))

        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return scaledImage ?? self
    }
}

The problem is that UIGraphicsGetImageFromCurrentImageContext() creates leaks because it returns an autorelease UIImage. Hence, when I want to assign this UIImage to a UIImageView, I need to wrap the assignation with autoreleasepool {...}. The problem is that I have 2000+ calls to scaleToSize(size:) in my app... Is there any other way to fix this ?

Thanks !

0 Answers
Related