user7865437
user7865437

Reputation: 812

Why does releasing a view controller cause a crash?

I always push a new view controller onto the stack like this:

 MyViewController *vc = [[MyViewController alloc] init];

[self.navigationController pushViewController:vc animated:YES];

[vc release];

And all works well when it comes to popping it off the stack with:

[self.navigationController popViewControllerAnimated:NO];

But now when I pop the vc off the stack I get a crash in main.m stating a bad access at line:int retVal = UIApplicationMain(argc, argv, nil, nil);

But now if I comment out [vc release] no more crash?

But why and surely this leaks memory as Im not releasing something I created?

Upvotes: 2

Views: 366

Answers (5)

Nianliang
Nianliang

Reputation: 3076

Perhaps you are mismanaging the memory of something inside of your vc.

This sentence from @brandontreb really helped me! I've struggled a whole day to fix the crash after a 'Received simulated memory warning', exactly descripted like:
Preventing bad access crash for popViewControllerAnimated in uinavigationcontroller setup

In my pushed view controller's loadView:, passed the view controller self to its dataSource's init:.

LayoutPickerDataSource *pickerDataSource = [[LayoutPickerDataSource alloc] initWithController:self];

while the dataSource class retained it like:

@property (nonatomic, retain) LayoutViewController *viewController;

Fix the crash just change to:

@property (nonatomic, assign) LayoutViewController *viewController;

and remove:

[viewController release];

bingo! I still don't know why! As viewController released in dealloc: of dataSource.

Upvotes: 0

chikuba
chikuba

Reputation: 4357

The reason why they are different is that you are not allocating the text objects, and therefore you are not the owner. It is the IB's job to alloc and realese them, which it does.

So if you also try to release it, it will cause problems.

Upvotes: 0

brandontreb
brandontreb

Reputation: 397

Your memory management looks fine. Perhaps you are mismanaging the memory of something inside of your vc. What does the dealloc method of MyViewController look like?

My guess is you are using the incorrect init method (perhaps initWithNibName:bundle:) and you are releasing ivars in dealloc that were never properly initialized.

Upvotes: 3

DreamOfMirrors
DreamOfMirrors

Reputation: 2157

Navigation controller will retain vc then, when vc is popped, navigationController releases it and vc deallocs.

So, you must leave the release code, it is correct.

I think you have to use a initWithNibName:bundle: insted of the init.

Upvotes: 0

Legolas
Legolas

Reputation: 12335

Did you try using it as a

@property

Upvotes: 0

Related Questions