iOS开发: How am I mismanaging memory in this code?

标签 ios objective-c iphone ipad memory-management

我刚刚添加了一些取自 Apple docs 的代码它展示了如何使用从 Nib 创建的自定义 UITableViewCells。我是 iOS 开发新手,所以我仍在学习正确的内存管理,并且代码对我来说并不完全清楚它是如何工作的。当我运行分配工具时,它在下面的代码中显示未分配的内存。具体来说,它显示在 View Controller 从导航堆栈中弹出后 UITableViewCell 仍保持事件状态...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{    
    static NSString *CellIdentifier = @"MyCustomCellIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"MyCustomCell_iPhone" owner:self options:nil];  //<--Allocations instrument complaining about this line
        cell = customCell;
        [self setCustomCell:nil];
    }

    return cell;
}

customCell 是在此 View Controller 中定义的实例变量,就像这样...

IBOutlet UITableViewCell *customCell;
@property (nonatomic, retain) IBOutlet UITableViewCell *customCell;

这段代码有问题吗?

非常感谢您的智慧!

最佳答案

我比较了文档中的代码:

if (cell == nil) {
    [[NSBundle mainBundle] loadNibNamed:@"TVCell" owner:self options:nil];
    cell = tvCell;
    self.tvCell = nil;
}

使用您的代码:

if (cell == nil) {
    [[NSBundle mainBundle] loadNibNamed:@"MyCustomCell_iPhone" owner:self options:nil];
    cell = [self customCell];
    [self setCustomCell:nil];
}

您分配 cell 的行似乎存在差异。 Apple 的示例代码使用 tvCell实例变量,而您使用 [self customCell]实例变量的属性 getter。这可能是原因吗?尝试改变

    cell = [self customCell];

    cell = customCell;

关于iOS开发: How am I mismanaging memory in this code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4347600/

相关文章:

python - appium ios python "an error occured while executing user supplied javascript"

iphone - 在iOS上,使用NSURLConnection时如何缓存更大的文件(1MB)?

ios - IOS5 上日期组件的星期数错误

ios - 需要建议在 iOS 开发中集成 Gmail 帐户

javascript - 移动 JavaScript 事件多次触发

使用通配符 ApppleId 的 iOs 克隆应用程序

ios - 从闭包中返回元组

ios - NSDate 问题

ios - 需要 UIButton 图像不透明度

objective-c - 动态给出一个相当于 NSButton 的 Key