views:

40

answers:

1

I know in vast of the cases I don't have to release static variable. However the following is the code for my model:

+ (UIImage*)imageForTag
{
    static UIImage *imgTag;

    if(imgTag == nil)
    {
        NSString* imageName = [[NSBundle mainBundle]
                           pathForResource:@"tag" ofType:@"png"];
        imgTag = [[[UIImage alloc]
                           initWithContentsOfFile:imageName] autorelease];
    }
    return imgTag;
}

and here is my data table part

- (UITableViewCell *)tableView:(UITableView *)tableView
                  cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView
                     dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc]
                               initWithStyle:UITableViewCellStyleDefault
                               reuseIdentifier:CellIdentifier] autorelease];
    }

    if (indexPath.row == 0) 
    {
        cell.imageView.image = [DataModel imageForSmtng];
    }
    else if(indexPath.row == 1)
    {
        cell.imageView.image = [DataModel imageForTag];
    }

    return cell;

This will crash on cell.imageView.image = [DataModel imageForTag] second time due to imageForTag is pointing to invalid address. If I add retain on that it will not crash. Is it wrong to remove autorelease from above and forget about imgTag references?

+1  A: 

It is wrong. Because when you call autorelease on the imgTag variable, you just released the object it points to. But, the imgTag variable still points to that range of memory. So, when you call the imgTag again, it is not nil, it still points to something, an invalid thing.

So, the solution should be either:

1/ You shouldn't release it at all

2/ You have to release it manually when you think that it is a good time to release it. And then remember to do: imgTag = nil

vodkhang
But I only know the good time in dealloc. For the rest I just give ownership to standard cell and I don't care any more. Turns out that cell is releasing it as well :( I guess I just don't autorelease it in the method above and release it when my app terminates, since I need it all the time.
Michael
yeah, if you need it all the time, you shouldn't release it at all. When you set it to the cell, the cell will retain it, but it will also release it after the cell go out. So, the static imgTag is still there, you don't need to worry
vodkhang