问题
Any idea on how to release the UIImage object picture in this case:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
UIImage *payload = [[UIImage alloc] initWithData:self.activeDownload];
UIImage *picture = [[UIImage alloc] init];
if (payload.size.width != kAppIconHeight && payload.size.height != kAppIconHeight)
{
CGSize itemSize = CGSizeMake(kAppIconHeight, kAppIconHeight);
UIGraphicsBeginImageContext(itemSize);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[payload drawInRect:imageRect];
picture = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
else
{
picture = payload;
}
self.activeDownload = nil;
[payload release];
self.imageConnection = nil;
[delegate ThumbDidLoad:self.indexPathInTableView Image:picture];
}
Thx for helping,
Stephane
回答1:
I'm having a hard time understanding why your "picture" variable has an alloc init at all. I agree with earlier answers to use autorelease, but perhaps something more like:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
UIImage *payload = [UIImage imageWithData:self.activeDownload];
UIImage *picture = nil;
if (payload.size.width != kAppIconHeight && payload.size.height != kAppIconHeight)
{
CGSize itemSize = CGSizeMake(kAppIconHeight, kAppIconHeight);
UIGraphicsBeginImageContext(itemSize);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[payload drawInRect:imageRect];
picture = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
else
{
picture = payload;
}
self.activeDownload = nil;
self.imageConnection = nil;
[delegate ThumbDidLoad:self.indexPathInTableView Image:picture];
}
Couple changes above:
1. UIImage *payload = [UIImage imageWithData:self.activeDownload];
. Changed this assignment to an autoreleased object since picture may be assigned to it. Note that the if
clause assigns picture
to an autoreleased object, so the else
clause should too and now it does since payload is now an autoreleased object.
2. UIImage *picture = nil;
instead of UIImage *picture = [[UIImage alloc] init];
. I did this since the picture assignment is NEVER used, so nil is actually valid since it will definitely be assigned in either the if
or else
clause.
3. No need for [payload release]
now that payload
is autoreleased.
回答2:
You need to make it autorelease
UIImage *picture = [[[UIImage alloc] init]autorelease];
回答3:
I think: [delegate ThumbDidLoad:self.indexPathInTableView Image:[picture autorelease]];
or
[delegate ThumbDidLoad:self.indexPathInTableView Image:picture];
[picture release];
But I see two problems in your code - leaks at picture = payload; and [payload release]; can release image, that is also indicated by the picture
来源:https://stackoverflow.com/questions/7431777/how-to-release-an-object-declared-into-a-method-and-passed-to-another-method