Question

I'm using a UINavigationController and I'm having trouble releasing objects when I push a new view. I want to set an object on the new controller before pushing it. The way I'm currently doing this is:

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

If I uncomment that last line then the program crashes when I navigate back throughout my controller. I also have another question regarding when/how to release an object. In the bookObj I have a mutable array of Page objects and I want to change the text of the current page object. I do this by:

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 that last line as well. It will let me navigate forward but when I navigate back and try to go forward again it crashes.

Autoreleasing the objects bring similar results. Please advise if you can. Thanks.

EDIT: When I do release the first example varOpenPageController and run the simulator with Leaks then the program seems to function properly. However, if I don't run Leaks then it crashes. Does anyone have any ideas why this might happen? Thanks.

Was it helpful?

Solution

It might pay to read the Apple Memory Management Document. The second item you don't need to release the pageObj as it only contains a reference to the actual item in the bookObj array. It's not the actual item if that makes sense. So what you are in effect doing is releasing the actual item from the array, so when you go back and try and access it, it isn't there.

The rule of thumb is: only release what you create.

OTHER TIPS

Your first example of pushing the view controller onto the navigation controller is correct with the release. If that is crashing when you come back, it probably means you have something wrong in the OpenPageViewController dealloc method, but something is wrong somewhere as the navigation controller retains your view controller and you should make sure you release it after you push (if you have allocated the view controller instance as you did in your code).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top