如何释放声明为方法并传递给另一个方法的对象?

时间:2011-09-15 13:38:34

标签: iphone ios ios4 uiimage delegation

在这种情况下,如何释放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];
}

求助,

的Stephane

3 个答案:

答案 0 :(得分:2)

你需要让它自动释放

UIImage *picture = [[[UIImage alloc] init]autorelease];

答案 1 :(得分:1)

我认为:       [委托ThumbDidLoad:self.indexPathInTableView Image:[picture autorelease]];

 [delegate ThumbDidLoad:self.indexPathInTableView Image:picture];
 [picture release];

但是我看到你的代码中存在两个问题 - 图片中的泄漏=有效负载;和[有效载荷释放];可以释放图像,也可以通过图片显示

答案 2 :(得分:1)

我很难理解为什么你的“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实际上是有效的,因为它肯定会在ifelse子句中分配。
   3. [payload release]现在不需要payload自动释放。