释放静态对象

时间:2010-08-02 05:44:54

标签: iphone objective-c memory-management

我知道在很多情况下我不必释放静态变量。但是以下是我的模型的代码:

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

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

这是我的数据表部分

- (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;

由于cell.imageView.image = [DataModel imageForTag]指向无效地址,第二次imageForTag会崩溃。如果我添加保留,它不会崩溃。从上面删除自动释放并忘记imgTag引用是错误的吗?

1 个答案:

答案 0 :(得分:1)

这是错的。因为当您在imgTag变量上调用autorelease时,您只需释放它指向的对象。但是,imgTag变量仍指向该范围的内存。所以,当你再次调用imgTag时,它不是零,它仍指向某个东西,这是无效的东西。

所以,解决方案应该是:

1 /你不应该发布它

2 /当您认为现在是发布它的好时机时,您必须手动释放它。然后记得要做:imgTag = nil

相关问题