views:

642

answers:

2

is my UIViewController freed when i call another controller ? How to release memory of controller when i push to another controller ? i take more than 40Mo and application leave because of LOW MEMORY(No leak).

[self.navigationController pushViewController:[[MainListController alloc] init:self] animated:NO];

@interface MainListController : UIViewController
...
- (id)init: (id)ref;

when i call on init function the dealloc of controller i was :

[ref dealloc];

i've this error :

objc[70754]: FREED(id): message isEqual: sent to freed object=0xe216b0
Program received signal:  “EXC_BAD_INSTRUCTION”.
  • (void)dealloc {[super dealloc];}
+3  A: 

No, you can't dealloc UIViewControllers that are not visible. What happens when the controllers on top pop off the navigation controller? What would the OS display then?

Instead you should implement the didReceiveMemoryWarning method in all your controllers. These should release (not dealloc) as much cached data as possible. Anything that you can recalculate or bring back in from disk should be considered.

This is better than just deallocing views that are not visible as you really don't know how much memory is available in advance. On an iPhone 3GS you might have plenty of memory left even when using 40Mb.

Stephen Darlington
Can i call manually the didReceiveMemoryWarning ?
NSchubhan
Just because you can doesn't mean you should. If you really want to release memory as you flip to MainListController, why not release the memory before you call the pushViewController method?
Stephen Darlington
if i call [self release];before [self.navigationController pushViewController:[[MainListController alloc] init:self] animated:NO];it's working, are you sure, i will not BAD acces ? because i release self and after i do self.navigation... Thanks
NSchubhan
No, you can't release the UIViewController while it's still in the navigation controller stack. You need to release cached data, not the controller itself.
Stephen Darlington
i found in another ask to do self.view = nil; is view and all subview will be release on my controller ? thk lot!
NSchubhan
+4  A: 

You cannot (and should not) release/dealloc a parent view controller when pushing a new one onto the navigation stack. You can unload the view by responding to the didReceiveMemoryWarning message.

There are several other problems with your code:

  1. Never ever call [obj dealloc] manually. Always use [obj release].
  2. Your init method name should be more descriptive as to not conflict with the predefined init method. You should also (possibly) strongly type the ref argument if you need to use it. Something like (id)initWithParent:(UIViewController*)ref would be better.
  3. Your code is leaking a MainListController object, since you are alloc/init'ing it and then handing it to navigationController. Change your code to [[[MainListController alloc] initWithParent:self] autorelease].
Jason