如何释放声明为方法并传递给另一个方法的对象?
在这种情况下,如何释放UIImage对象图片的任何想法:
- (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]; }
感谢帮助,
斯特凡
我很难理解为什么你的“picture”变量有一个alloc init。 我同意早期使用自动释放的答案,但可能更像是:
- (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]; }
情侣改变如上:
1. UIImage *payload = [UIImage imageWithData:self.activeDownload];
。 将此分配更改为自动释放的对象,因为可能会为其分配图片。 请注意, if
子句将picture
分配给自动释放的对象,因此else
子句也应该,现在它也可以,因为有效负载现在是一个自动释放的对象。
2. UIImage *picture = nil;
而不是UIImage *picture = [[UIImage alloc] init];
。 我这样做是因为图片分配从未使用过,所以nil实际上是有效的,因为它肯定会在if
或else
子句中赋值。
3.现在payload
是自动释放的,无需[payload release]
。
你需要让它自动释放
UIImage *picture = [[[UIImage alloc] init]autorelease];
我想:[委托ThumbDidLoad:self.indexPathInTableView Image:[picture autorelease]];
要么
[delegate ThumbDidLoad:self.indexPathInTableView Image:picture]; [picture release];
但是我看到你的代码中存在两个问题 – 图片中的泄漏=有效负载; 和[有效载荷释放]; 可以释放图像,这也是图片所示