NikGreen
NikGreen

Reputation: 700

Effective long text drawing in UITableViewCell

I'm fetching an array of comments, which I need to display in a tableView.

The tableView has custom cells for displaying content. The problem is that comments text can vary in its length and I'm facing a serious memory growth while scrolling the tableView.

Several approaches I've tried to display the text:

Besides the tableView seems to not be dequeueing my custom cells, so the memory keeps growing while the tableView is being scrolled (my cells are now having 1.5К symbols of text)

enter image description here

Cells are created like this, so nothing special

- (UITableViewCell*)            tableView: (UITableView*) tableView
                    cellForRowAtIndexPath: (NSIndexPath*) indexPath
{
     [tableView registerClass: [CommentCell class] forCellReuseIdentifier: kCommentCellId];

     CommentCell* cell = [tableView dequeueReusableCellWithIdentifier: kCommentCellId
                                                         forIndexPath: indexPath];

     Comment* comment = [self.comments objectAtIndex: indexPath.row];

     cell.comment = comment;

     return cell;
}

Custom setter for comment property

- (void) setComment: (Comment*) aComment
{
    self.commentLabel.text = aComment.comment;

    [self setNeedsLayout];
}

Adding comment label inside the cell

- (id) initWithStyle: (UITableViewCellStyle) style
 reuseIdentifier: (NSString*) reuseIdentifier
{
   self = [super initWithStyle: style reuseIdentifier: reuseIdentifier];

   if (self)
   {
        // Comment label
        //
        self.commentLabel = [UILabel new];

        self.commentLabel.textColor     = [UIColor colorWithRed: 0.21f green: 0.21f blue: 0.21f alpha: 1.00f];
        self.commentLabel.font          = [UIFont helveticaNeueRegularOfSize: 13.33f];
        self.commentLabel.numberOfLines = 0;
        self.commentLabel.lineBreakMode = NSLineBreakByWordWrapping;

        [self.contentView addSubview: self.commentLabel];
    }

    return self;
 }

Upvotes: 0

Views: 226

Answers (2)

NikGreen
NikGreen

Reputation: 700

The problem was that I somehow was setting the tableview frame height to the height of tableviews' content, so in fact all the cells were visible - thus not being reused.

Thanks @matt for pushing me in the right direction.

Upvotes: 1

matt
matt

Reputation: 535557

The problem is presumably that you are wrongly retaining and never releasing cell objects in code you are not showing, such as whatever it is you are doing to calculate the varying row heights.

It has nothing to do with the labels themselves, or anything having to do with displaying text of varying heights. I've made tables whose rows vary in height with text of varying length displayed in labels or text drawn directly, and there's no such leakage.

You might want to look over the section from my book on this topic.

Upvotes: 2

Related Questions