【问题标题】:UITableViewCell custom initialization from nibUITableViewCell 从 nib 自定义初始化
【发布时间】:2012-05-09 22:42:50
【问题描述】:

下面的代码会有多错:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    NSArray *array = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil];
    for (id currentObject in array) {

        if ([currentObject isKindOfClass:[self class]]) {
            self = [currentObject retain];
        }
    }

    return self;
}

我正在尝试从 nib 文件中调出一个自定义 UITableViewCell,问题是 Leaks Instruments 说里面有泄漏:

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

static NSString *CellIdentifier = @"Cell";

    CPVideoGenTVCell *cell = (CPVideoGenTVCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {

        cell = [[[CPVideoGenTVCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        cell.titleLbl.textColor = [UIColor colorWithRed:0.992 green:0.933 blue:0.0 alpha:1.0];

    }

    CPTempVideo *aVideo = [self.videos objectAtIndex:indexPath.row];

    cell.seasonLbl.text = [NSString stringWithFormat:@"Season %@", [self romanNumberFromArabic:aVideo.season]];
    cell.titleLbl.text = [NSString stringWithFormat:@"%2i - \"%@\"",aVideo.idVideo, aVideo.chapterName];
    cell.managedImg.url = aVideo.thumbnail;

    [[CPDataManager sharedDataManager] manageImage:cell.managedImg];

    return cell;
}

【问题讨论】:

  • 显示您的cellForRowAtIndexPath: 代码。
  • 你运行Analyze了吗?它可能会为您提供泄漏位置的线索。
  • 分析没有显示任何东西......我认为这段代码“应该”工作,但它可疑......

标签: ios memory-leaks uitableview xib


【解决方案1】:

认为问题出在保留上,但不明白你为什么要用 initWithStyle 做这些疯狂的事情..

if ([currentObject isKindOfClass:[self class]]) {
  self = currentObject;
}

【讨论】:

  • :D 只是覆盖初始化......虽然有更简洁的方法可以做到这一点,但我喜欢尝试。您的解决方案破坏了 cellForRowAtIndexPath 内的应用程序:
  • Instruments 会告诉您泄漏的确切位置......因此您必须发布确切的代码行或代码块
【解决方案2】:

我找到了另一种选择:

+ (id)cellWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    NSArray *array = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil];
    for (id currentObject in array) {

        if ([currentObject isKindOfClass:[self class]]) {
            return currentObject;
        }
    }

    return nil;
}

只需返回一个自动释放的对象并在 cellForRowAtIndexPath 中处理它:

CPTempHeadCell *headCell = (CPTempHeadCell *)[tableView dequeueReusableCellWithIdentifier:HeadCellIdentifier];
if (headCell == nil) {

    headCell = [CPVideoGenTVCell cellWithStyle:UITableViewCellStyleDefault 
                                       reuseIdentifier:CellIdentifier];

【讨论】:

    猜你喜欢
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多