views:

64

answers:

1

Hello there,

I'm creating some temporary files in the iPad simulator. To test my file creation, I create the file and then read it back. Here's some code to show this:

-(NSString *) writeToTempFile:(UIImage*) image{
NSString *path = [self createTemporaryFile];
NSLog(@"path: %@", path);
NSData *data = UIImageJPEGRepresentation(image, 1);
[data writeToFile:path atomically:YES]; 
free(data);
return path;
}

-(UIImage *) readTempFile:(NSString *) path{
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
UIImage *image = [[UIImage alloc] initWithData:data];
return image;
}

I call these methods one after another, before a final function writes out the UIImage to the photo album.

UIImageWriteToSavedPhotosAlbum(image2, self, nil, nil);

The problem is, this always crashes my app on the third time it is executed. First and second time it successfully does all of this and stores to the album. Third time it crashes to Home. Any ideas?

+5  A: 
NSData *data = UIImageJPEGRepresentation(image, 1);
[data writeToFile:path atomically:YES]; 
free(data);

The NSData returned from UIImageJPEGRepresentation is -autoreleased. There is no need to free() it. And it is wrong to free() any Objective-C objects — send a -release message instead.

Please read through the Memory Management Programming Guide.

KennyTM
Wonderful. Thanks a bundle!
mtc06