来自nib的UITableViewCell自定义初始化

时间:2012-05-09 22:42:51

标签: ios memory-leaks uitableview xib

下面的代码有多么错误:

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

我找到了另一种选择:

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