views:

54

answers:

2

I'm trying to present a viewcontroller modally:

- (IBAction)addReference {

    ReferenceAddViewController *referenceAddViewController = [[ReferenceAddViewController alloc] initWithNibName:@"ReferenceAddViewController" bundle:nil];
    [referenceAddViewController setDelegate:self];

    [self presentModalViewController:referenceAddViewController animated:YES];

    [referenceAddViewController release];
}

However, if I call [referenceAddViewController release], later on when the modal view is dismissed, my app crashes with "[CALayer release]: message sent to deallocated instance 0x4b90370".

Doing a stack trace and reference count history in Instruments didn't give away anything conclusive, with only two history steps.

  • 0: Retain count 1 - Malloc by presentModalViewController in my code.
  • 1: Retain count -1 - nothing in my code apart from main.m

It is very interesting on how the reference count skips from 1 to -1? Does Instruments record every reference count change?

How would I go about debugging this issue further?

A: 

There is no need to release the view controller after the modal view controller is dismissed. presentModalViewController:animated: increments the retainCount by 1, and dismissModalViewControllerAnimated: decrements it by 1.

So when you allocate it (+1), present it (+1) and release it (-1), and later on it is dismissed (-1) the retainCount will be 0, the object will be deallocated, and all is fine. If you try to release it after it has been dismissed, the object has already been deallocated and it won't work.

Douwe Maan
A: 

Thanks for your reply, I always thought that when you call alloc, you increase the reference count to 1 at the start?

In that case, would the reference count become 2 when the presentModalViewController:animated: is called?

When the modal view is dismissed, it would become 1 again, but never 0 because I didn't release?

redshift5
calling `[referenceAddViewController release];` releases the object that you alloc'd. calling `presentModalViewController` does not alloc anything by you, so therefore you are not responsible for releasing anything. you are only responsible for objects you explicitly alloc
iWasRobbed