saving array of images with UIImagePNGRepresentation memory warning swift

255 views Asked by At

I'm capturing randomly-sized/shaped sections of a UIView and saving to disk using UIImagePNGRepresentation. The files save as expected, but when I run on a device, I get the dreaded "Received memory warning", even though all I'm doing is saving files in a loop and not displaying them:

UIGraphicsBeginImageContextWithOptions(bbox.size, false, 0)
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.25).CGColor)
CGContextAddRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, bbox.width, bbox.height))
CGContextFillPath(UIGraphicsGetCurrentContext())

let strokeImage = UIGraphicsGetImageFromCurrentImageContext()
let strokeFile = "stroke_\(strokeBezierArrayMemory.count).png"
let dataPng = UIImagePNGRepresentation(strokeImage)
let fileURL = folderURL!.URLByAppendingPathComponent(strokeFile)  //println("\(fileURL)")
if (dataPng.writeToURL(fileURL, options: .AtomicWrite, error: &error) ) {
  //println ("WROTE \(fileURL)")
} else {
  print (error)
}

I've seen similar posts, but no answers that solve my problem. This post suggests using AVFoundation, but I'm hoping I can stick to UIImagePNGRepresentation.

I also tried wrapping the NSData part of the code in an autoreleasepool closure to no avail:

autoreleasepool({ () -> () in
  let strokeFile = "stroke_\(strokeBezierArrayMemory.count).png"
  let data = UIImagePNGRepresentation(strokeImage)
  let fileURL = folderURL!.URLByAppendingPathComponent(strokeFile)  //println("\(fileURL)")
  if (data.writeToURL(fileURL, options: .AtomicWrite, error: &error) ) {
    //println ("WROTE \(fileURL)")
  } else {
    print (error)
  }
})

Is there a way to force NSData to release each dataPng once written to disk?

0

There are 0 answers