how do I avoid this memory leak when getting a UIImageView?
I have a helper method that loads images for me. I want to be able to use this code all over my app so I created this:
+(UIImageView *)开发者_StackOverflow getSignature: (NSString *) aPONumber {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *newPath =[documentsPath stringByAppendingPathComponent: [NSString stringWithFormat:@"%@-signature.jpg", [aPONumber stringByReplacingOccurrencesOfString:@"/" withString:@""]]];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:newPath];
if(fileExists)
{
return [[UIImageView alloc] initWithImage:[[UIImage alloc] initWithContentsOfFile:newPath]];
} else {
return nil;
}
}
Would this be a good place to use autorelease? Something like this:
return [[[UIImageView alloc] initWithImage:[[[UIImage alloc] initWithContentsOfFile:newPath] autorelease]]autorelease];
Short answer: Yes.
You can use autorelease there and don't have to worry about releasing your UIImageViews or UIImages anymore. Just add them to an UIView and they'll get automatically deallocated once they are removed from the UIView or the UIView gets deallocated.
精彩评论