iOS dealloc crash

2.2k Views Asked by At

find a strange code here I have a viewcontroller, it has an array with books, and click the cell, then push to a detailViewController, detailVC has a variable infoDict,

 @property (nonatomic,retain) NSMutableDictionary * infoDict;

navigationController push

DetailViewController * tDVC = [[DetailViewController alloc] init];
tDVC.infoDict = infoDict;
[self.navigationController pushViewController:tDVC animated:YES];
[tDVC release];

tap the back button, pop back, and inside dealloc of DetailVC

-(void)dealloc
{
    [super dealloc];

    NSLog(@"before %d",infoDict.retainCount);
    [infoDict release];
}

but when I tap back, in this dealloc app crashes randomly, EXC_BAD_ACCESS.

when move [super dealloc] to the bottom of dealloc, it seems back to normal. pls help me to understand this , many thanks

3

There are 3 best solutions below

1
On

[super dealloc] deallocates the object itself. If you type dealloc and let Xcode autocomplete, you get this:

- (void)dealloc
{
    <#deallocations#>
    [super dealloc];
}

Meaning you should release objects and properties before you call [super dealloc]

1
On

Your -dealloc implementation is out of order. The call to -[super dealloc] must be the absolute last invocation in the dealloc method. When you access the ivar infoDict, the compiler is really doing something like self->infoDict and by this point, self has been deallocated and is no longer valid.

If at all possible, I recommend using ARC instead of manually managing memory.

7
On

Try

its better if you use self.infoDict = nil; instead of [infoDict rlease];

-(void)dealloc
{
  NSLog(@"before %d",infoDict.retainCount);
  [infoDict release];

  [super dealloc];
}