Filo
Filo

Reputation: 57

How to reuse a UIImage

I'm using some sample code I got from a tutorial to create basically a snapshot using AVCamRecorder. It doesn't save a picture, it just displays it in a little rect under the live camera view whenever I click a button. It seemed to be allocating more and more memory each time I clicked the button to update the image, so I put an if (image) {[image release]} and then continued with the rest of the code to capture the image. The problem I ran into there is that eventually I hit an EXC_BAD_ACCESS if I click the button fast enough repeatedly. I tried inserting an if (image) immediately before assigning it to my view, but I still get EXC_BAD_ACCESS. I tried adding an [NSThread sleepForTimeInterval:1] at the end, but that didn't help either. I still get the EXC_BAD_ACCESS after clicking the button several times. Is there a proper way to reuse this view? Thanks

if (image) {
    [image release];
    exifAttachments = nil;
}
[[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:stillImageConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
    exifAttachments = CMGetAttachment(imageDataSamplebuffer, kCGImagePropertyExifDictionary, NULL);
    if (exifAttachments) {
        // NSLog
    } else {
        // NSLog
    }
    NSData *imagedata = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
    image = [[UIImage alloc] initWithData:imageData];
    if (image) {
        self.capturedPicView.image = image;
    }
}];`

Upvotes: 1

Views: 1272

Answers (1)

SVD
SVD

Reputation: 4753

Is the image variable declared as __block? If not, you may get all sorts of weird things because you can't modify it within a block.

You probably don't need a separate image variable - just do:

self.capturedPicView.image = [[[UIImage alloc] initWithData:imageData] autorelease];

in your block.

P.S. And it looks like your original memory leak was due to not releasing the new image - you could have added autorelease to UIImage creation or just release it right after assigning (UIImageView.image retains it anyway):

image = [[UIImage alloc] initWithData:imageData];
if (image) {
    self.capturedPicView.image = image;
    [image release];
}

Upvotes: 3

Related Questions