0

Thanks for checking out my post.

So on line image!.drawInRect(rect!), I get the EXC_BAD_ACCESS Code 1 error and I can't figure it out for the life of me. I have enabled Zombies in the Run Scheme, and nothing prints out (maybe I'm doing that wrong too?), I have println() seemingly all of my variables and nothing is nil.

I would like to note that this code works twice and then fails the 3rd time it is called, majority of the time. In my app, you take a picture, then it takes you to edit the picture (when this function is called). When I go back to my camera to take a picture, and return to edit it (on the 3rd time), I get this error.

Also, this method is called in viewDidAppear()

Any help is appreciated. I'm about to pull my hair out!

       var rect: CGRect?
    var image: UIImage?
func convertCIImageToUIImage(cIImage: CIImage) -> UIImage {

    println(cIImage)

    let size: CGSize = filteredImageView.inputImage.size
    println(filteredImageView.inputImage.size)

    UIGraphicsBeginImageContext(size)

    rect = CGRect(origin: CGPointZero, size: size)
    image = UIImage(CIImage: filteredImageView.filter.outputImage)

    println(UIGraphicsGetCurrentContext())
    println("size: \(size)")
    printAllObjects()
    println()

    image!.drawInRect(rect!)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    image = nil
    rect = nil

    let finalImage = UIImage(CGImage: newImage.CGImage!, scale: 1.0, orientation: UIImageOrientation.Right)
    return finalImage!
}
justColbs
  • 1,504
  • 2
  • 18
  • 28

2 Answers2

3

Solved it!

My function was over-engineered by a long-shot. A simple return UIImage(CIImage: cIImage)! solved my problem and replaced all of the code above. That's what I get for copying code online! Lesson learned. Thanks for the help!

justColbs
  • 1,504
  • 2
  • 18
  • 28
2

Since the line in question force-unwraps two optionals maybe you're unwrapping a nil (which generates the error). Try using optional binding for safe unwrapping:

if let safeRect = CGRect(origin: CGPointZero, size: size),
   let safeImage = UIImage(CIImage: filteredImageView.filter.outputImage)
{
   safeImage.drawInRect(safeRect)
}

This way, if construction of either the CGRect instance or the UIImage instance fails, the line inside braces won't be executed.

MustangXY
  • 358
  • 2
  • 16
  • Hey thanks for the response. So commented out my line and replaced it with yours. And the same thing is happening. It fails on `safeImage.drawInRect(safeRect)`. Very odd. Any other ideas? – justColbs Sep 14 '15 at 15:17
  • Pasting your code in a Playground gives me a good bunch of errors regarding `filteredImageView`. What is it? – MustangXY Sep 14 '15 at 15:29
  • It is a custom class. I solved the problem. Check below. – justColbs Sep 14 '15 at 16:01