I ran instrument in xcode4 and it told me there were two leaks in the following code (noted by ****). I thought I had taken care of memory release with code at pt. A and pt. B.
I read through some related topics here but still couldn’t figure out why and how to fix them.
Another question is whether the release at pt. A is necessary.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//Get the dialog id
NSDictionary *rowData = [dialogs objectAtIndex:indexPath.row];
NSInteger dialogId = [[rowData objectForKey:@"id"] intValue];
DialogViewController *detailViewController = [[DialogViewController alloc] initWithNibName:@"DialogViewController" bundle:nil];
detailViewController.dialogId = dialogId;
NSString *title = [NSString stringWithFormat:@"%d. %@", [[rowData objectForKey:@"id"] intValue], [rowData objectForKey:@"title"]];
****** i 6.8%
[detailViewController.dialogTitle release]; // pt. A
detailViewController.dialogTitle = [title retain];
[self.navigationController pushViewController:detailViewController animated:YES];
****** i 93.2%
[detailViewController release]; // pt. B
}
Thanks much in advance!
Lu
Whether the release/retain calls are necessary at Point A depend on how you defined your dialogTitle property.
If you defined it as @property (retain) then you don’t need to release the old value or retain the new value because when you assign a value to a (retain) property, it is automatically retained. Also when you assign a new value to a (retain) property, the old value is released, so you don’t have to do the release either. All you would need in this case is:
If you defined dialogTitle as (assign) then you DO need to do the release/retain in Point A.
As for Point B, you do need to release there because if you don’t, your detailViewController object will never get deleted. When it is alloc/inited, it gets a retain count of 1. When you push the view controller, it gets retained (so now has a retain count of 2). Then you release at the end of the method and it’s retain count goes down to 1. Then, when the navigation controller that contains it is dismissed, it will get released again, it’s retain count will go to 0 and it will get deleted.
As an alternative to releasing the detailViewController at the end of the method, you could just autorelease it when you alloc/init it and remove the release at the end of the method. By autoreleasing it, you are essentially marking it to be released automatically the next time the autorelease pool is cleared out (which will be soon after this method exits)