4

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 !

Dliix
  • 718
  • 1
  • 7
  • 20
  • Which iOS version are you targeting ? You can use UIGraphicsImageRenderer in iOS10+ – nathan Aug 01 '17 at 15:35
  • I am targeting iOS9+, however I will check `UIGraphicsImageRenderer` so I can add it to iOS 10+ devices. Thanks – Dliix Aug 01 '17 at 15:39
  • Have you tried https://stackoverflow.com/a/5122107/2124535 ? Here's a simple example of `UIGraphicsImageRenderer`: https://developer.apple.com/documentation/uikit/uigraphicsimagerenderer#overview – nathan Aug 01 '17 at 15:40
  • Yes, the thing is that the `autoreleasepool` has to be outside my centralized method. And I have 2000+ calls to this methods throughout the app. I'm looking for a way to fix the leaks in a centralized method rather than changing my whole code. – Dliix Aug 01 '17 at 15:46
  • I'm having the same issue. Could you explain to me how autorelease works? Why does it have to be outside your scaleToSize method? – andrei Dec 04 '17 at 09:49
  • The variable you want to release has to be into your `autoreleasepool`, but my `scaleToSize` method returns the image I want to free, thus `autoreleasepool` will not work from within the method because the image reaches an higher scope. – Dliix Dec 06 '17 at 10:12

0 Answers0