views:

32

answers:

1

I have a UITableView with a cellForRowAtIndexPath method that creates a UITextView, then adds it to a cell. No memory leaks were detected, but when running Instruments (Object Allocations), the Net memory is on a one-way trip to 18 MB, where it crashes.

My app constantly adds and deletes cells in the tableView datasource, but because the TextView is released, I can see no way memory could be piling up.

Here is my cellForRowAtIndexPath code:

static NSString *cellIdentifier=@"Cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if (cell==nil) {
    // Build cell
    cell=[[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
}

cell.selectionStyle=UITableViewCellSelectionStyleNone;

UITextView *tv=[[UITextView alloc] initWithFrame:CGRectMake(0, 0, 320, 95)];
tv.font=[UIFont fontWithName:@"Helvetica-Bold" size:16];

tv.text=@"My Cell Text";

[cell addSubview:tv];
[tv release];

return cell;

Thanks in advance!

+2  A: 

You add UITextView every time a cell is fetched. If it comes from cache, it already has one as a subview, so now it has two of them, then three, then four...

So only add them to new cells:

if (cell==nil) {
    // Build cell
    cell=[[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;

    UITextView *tv=[[UITextView alloc] initWithFrame:CGRectMake(0, 0, 320, 95)];
    tv.font=[UIFont fontWithName:@"Helvetica-Bold" size:16];
    tv.tag = 42; // Or whatever, if you don't want to use custom cells
    [cell addSubview:tv];
    [tv release];
}

UITextView *textView = (UITextView *) [cell viewWithTag:42];
textView.text=@"hi";
Eiko
Thanks, that works great, except what if the dataSource is changed as in my case? The cell still displays the cached data?
pop850
It will display whatever you set the text to, "hi" in this case... If you need different text, this is the place to set it - depending on the indexPath. If you need to change it while displayed, you need to reload the given indexPath, i.e. [self.tableView reloadRowsAtIndexPaths:... withAnimation:...];
Eiko