views:

280

answers:

2

I am running the following code in tableView:cellForRowAtIndexPath:

File *file = [[File alloc] init];
file = [self.fileList objectAtIndex:row];
UIImage* theImage = file.fileIconImage;

cell.imageView.image = theImage;
cell.textLabel.text = file.fileName;
cell.detailTextLabel.text = file.fileModificationDate;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

return cell;

I ran the leaks tool and found out that the File object is leaking because I am not releasing it. So I added the release prior to returning the cell where I thought it was safe (as shown below):

File *file = [[File alloc] init];
file = [self.fileList objectAtIndex:row];

UIImage* theImage = file.fileIconImage;

cell.imageView.image = theImage;
cell.textLabel.text = file.fileName;
cell.detailTextLabel.text = file.fileModificationDate;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
[file release];

return cell;

Now, when I run the application it crashes. Are the UITableViewCells still referencing the file object? What is the approach to use here to make sure I am not leaking memory?

+1  A: 

Yes, the cell is still referencing it at the point you are releasing it, so the app crashes.

You need to use autorelease when you declare it, as follows:

File *file = [[[File alloc] init] autorelease];

Then, don't call the [file release] part. As soon as it's not referenced any more (ie when you stop using the cell) it will be autoreleased at the start of the next run loop.

h4xxr
+6  A: 
File *file = [[File alloc] init];
file = [self.fileList objectAtIndex:row];

Well, here you're first allocating a new File and then you discard the pointer and apparently get another existing object from an array. That's the one you release if you call release later on. The one you call release on in the end is not the one you allocated. The pointer to the freshly allocated one is lost and thus leaks.

Probably it crashes because self.fileList contains a pointer to an already destructed object thereafter.

Maybe you meant to write just

File *file = [self.fileList objectAtIndex:row];
Rüdiger Hanke
Fair, hadn't looked at that bit, had only suggested the autorelease with the alloc/init... but you're right, he doesn't need to alloc/init the file object at all!
h4xxr