views:

43

answers:

2

I encountered some strange memory leaks executing following code on iPhone device:

@implementation TestViewController
@synthesize myButton;

- (IBAction)buttonPressed {
    ABPeoplePickerNavigationController* selectContactViewController = nil;

    selectContactViewController = [[ABPeoplePickerNavigationController alloc] init];
    selectContactViewController.peoplePickerDelegate = self;
    [self presentModalViewController:selectContactViewController animated:YES];
    [selectContactViewController release];
}  

Releasing the picker simple done as follows:

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {

    [self dismissModalViewControllerAnimated:YES];
}

Instruments marks "selectContactViewController = [[ABPeoplePickerNavigationController alloc] init];" as leaking. Any idea why?

A: 

You might want to construct your Picker control like so:

ABPeoplePickerNavigationController* selectContactViewController = nil;

selectContactViewController = [[[ABPeoplePickerNavigationController alloc] init] autorelease];
selectContactViewController.peoplePickerDelegate = self;
[self presentModalViewController:selectContactViewController animated:YES];

When you present the modal view controller, it will retain the view on its own. That's how it's able to still pass you an instance of the view controller to your delegate. Best bet is to set the view controller to be autoreleased, so when it gets popped from the navigation controller, the NSAutoReleasePool will garbage collect it.

Michael Nachbaur
Reference counting is not garbage collection. iPhone OS does not do garbage collection.
tc.
You are correct tc but I tried anyway using autorelease but that didn't work...I am testing on 3.1.3 Is it possible there is a leak in that OS version?
Joshua
A: 

Just a comment - do you use any protocol like UINavigationControllerDelegate in the interface declaration?

I encountered a situation where just referencing this protocol caused a similar leak message.

I am using the ABPeoplePickerNavigationControllerDelegate protocol but even for the sole purpose of verifying it's not causing the leak, I can't see how not to include it...
Joshua