How to release an object declared into a method and passed to another method?

前端 未结 3 801
鱼传尺愫
鱼传尺愫 2021-01-29 09:45

Any idea on how to release the UIImage object picture in this case:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    UIIm         


        
3条回答
  •  鱼传尺愫
    2021-01-29 10:34

    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.

提交回复
热议问题