Freeing Objects Using UINavigationController

I am using UINavigationController and I am having problems releasing objects when I push a new view. I want to set an object to a new controller before pushing it. The way I am doing it now:

OpenPageViewController *varOpenPageController = [[OpenPageViewController alloc] initWithNibName:@"OpenPageViewController" bundle:nil];
varOpenPageController.bookObj = bookObj;
[[self navigationController] pushViewController:varOpenPageController animated:YES];
//[varOpenPageController release];

      

If I uncomment this last line, the program crashes when I go back all over the controller. I also have another question regarding when / how to release an object. In bookObj I have a mutable array of page objects and I want to change the text of the current page object. I'm doing it:

Page *pageObj = [[bookObj pagesArray] objectAtIndex:currentPage];
pageObj.page_Text = textView.text;
[[bookObj pagesArray] replaceObjectAtIndex:currentPage withObject:pageObj];
//[pageObj release];

      

The program crashes if I uncomment this last line. This will allow me to move forward, but when I go back and try to go forward, it works.

Object auto-implementation produces similar results. Please advise if you can. Thank.

EDIT: When I release the first varOpenPageController example and run the simulator using Leaks, the program works fine. However, if I don't run leaks, it crashes. Anyone have any ideas why this might be happening? Thank.

+1


source to share


2 answers


You may need to read Apple's Memory Management Document . Second element that you don't need to free pageObj as it only contains a reference to the actual element in the bookObj array. This is not the actual point, if that makes sense. So what you are actually doing is freeing the real element from the array, so when you go back and try to access it, it isn't there.



Rule of thumb: just let go of what you create.

+2


source


Your first example of pushing a view controller to a navigation controller is correct with release. If this happens when you return it probably means that you have something wrong in the dealloc method of the OpenPageViewController, but something is wrong somewhere when the navigation controller saves your view controller and you have to make sure that you release it after clicking (assuming you have an allocated instance of the view controller as you did in your code).



+2


source







All Articles