Swift UIGraphicsGetImageFromCurrentImageContext memory leak

I have a centralized resize method 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 what UIGraphicsGetImageFromCurrentImageContext()

creates leaks because it returns autorelease UIImage

. Hence, when I want to assign this one UIImage

to UIImageView

, I need to associate the assignment with autoreleasepool {...}

. The problem is I have 2000+ calls scaleToSize(size:)

in my application ... is there any other way to fix this?

Thank!

+3


source to share





All Articles