调用reloadData时自定义UITableViewCell内存泄漏

时间:2014-06-09 09:24:16

标签: ios iphone objective-c uitableview

我有一个UITableView,可以加载一些自定义的UITableViewCells。这些自定义单元格分配了一些UIButton,并将这些按钮添加到自定义单元格的contentView中。当在tableView上反复调用reloadData时,似乎这些UIButtons正在慢慢泄漏内存。我正在使用ARC,iOS 7。

这里是创建单元格的地方:

- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *simpleTableIdentifier = @"PostCell";
    PostCell *cell = [_tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) {
        cell = [[PostCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
    return cell;
}

这是自定义单元格的init方法:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.height = 0;
        self.backgroundColor = [UIColor clearColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self addInteractionContainer];
    }
    return self;
}

最后是addInteractionContainer方法(如果我不打电话给这个方法,我就不会发现泄漏):

- (void)addInteractionContainer {
    //interaction container
    UIView* interactionContainer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 80)];
    [interactionContainer setBackgroundColor:[UIColor ProseSepiaColor]];

    //like button
    LikeButton* likeButton = [[LikeButton alloc] initWithFrame:CGRectMake(10, 10, 75, 30) liked:([post.yourVote intValue] > 0)];
    [likeButton addTarget:self action:@selector(likePost:) forControlEvents:UIControlEventTouchUpInside];
    [interactionContainer addSubview:likeButton];

    //comment button
    CommentButton* commentButton = [[CommentButton alloc] initWithFrame:CGRectMake(likeButton.frame.origin.x + likeButton.frame.size.width + 10,
                                                           10, 105, 30)];
    [commentButton addTarget:self action:@selector(segueToComments:) forControlEvents:UIControlEventTouchUpInside];
    [commentButton setNumComments:self.post.numComments];
    [interactionContainer addSubview:commentButton];
    [self.contentView addSubview:interactionContainer];
    self.height += interactionContainer.frame.size.height;
}

1 个答案:

答案 0 :(得分:0)

try this
- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *simpleTableIdentifier = @"PostCell";
    PostCell *cell = [_tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if(cell!=nil)
{
     cell=nil;
}
    if (cell == nil) {
        cell = [[PostCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
    return cell;
}