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

前端 未结 3 796
鱼传尺愫
鱼传尺愫 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:30

    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

    0 讨论(0)
  • 2021-01-29 10:32

    You need to make it autorelease

    UIImage *picture = [[[UIImage alloc] init]autorelease];
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题