【问题标题】:Custom UITableViewCell, autorelease and other method自定义UITableViewCell、autorelease等方法
【发布时间】:2012-03-19 10:21:22
【问题描述】:

(对不起我的英语:-) 我正在加载一个自定义 UITableViewCell:

static NSString *CellIdentifier = @"ReminderCell";
ReminderCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {
    NSLog(@"Alloco nuova cella");
    NSArray *objectsInNib = [[NSBundle mainBundle] loadNibNamed:@"ReminderCell" owner:nil options:nil];
    for(id currentObject in objectsInNib)
    {
        if([currentObject isKindOfClass:[ReminderCell class]])
        {
            cell = (ReminderCell *)currentObject;
            break;
        }
    }
} //fine caricamento cella dal Nib

return cell;

我将所有者设置为 nil,因为我有此单元格的 .m 和 .h,并且希望将插座放在它自己的文件中,而不是在 UITableViewController 中。它工作正常。

我的问题是关于在这种情况下正确的内存管理。

我知道 loadNibNamed 返回一个自动释放的数组。 此外,我知道自动释放池在当前循环结束时耗尽。 因此,在返回之前应该不需要保留我的自定义单元格。

但是,我多次听说您应该假设自动释放的对象只能保证在发送自动释放的方法结束之前存在。 假设这一点,我应该立即保留单元格,然后自动释放它:

cell = [[(ReminderCell *)currentObject] retain];
//code...
[cell autorelease];
return cell;

这是正确的还是我不应该担心这个? 谢谢

【问题讨论】:

  • 对不起,很明显autorelease应该在if里面,紧跟在cell = [[(ReminderCell *)currentObject]retain];否则我可能会错误地过度释放其他单元格(例如出队的单元格)

标签: objective-c memory-management uitableview loadnibnamed


【解决方案1】:

这不是必需的。对象不是guaranteed to live only until the end of the method where the autorelease was sent - 方法在这里无关紧要。对象将在autorelease 方法添加到的自动释放池耗尽后被释放。由于您的方法中没有自动释放池管理,currentObject 在执行期间不会收到release

例如(当然没有 ARC):

id obj;
NSAutoreleasePool *pool = [NSAutoreleasePool new];
...
obj = [other object];
...
[pool drain];

[obj doSomething]; // DANGEROUS

在你的情况下是这样的:

id obj;
...
obj = [other object];
...
[obj doSomething]; // SAFE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多