user393964
user393964

Reputation:

Memory management with UINavigationController view

My application started out as viewbased but I had to change to navigation based later on. The way I did this was by creating a UINavigationController member in my AppDelegate and calling pushViewController in the didFinishLaunchingWithOptions method:

@property (nonatomic, retain) IBOutlet UINavigationController *navigator;

// didFinishLaunchingWithOptions implementation
MainController *mainView = [[MainController alloc] initWithNibName:@"MainController" bundle:nil];
navigator = [[UINavigationController alloc]init];
[navigator pushViewController:newSongView animated:YES];
[mainView release];

In my MainController view I have a button that calls this method and sends the user to the next view:

- (IBAction)newViewLoader:(id)sender {
    SecondViewController *secVC = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
    [self.navigationController pushViewController:secVC animated:YES];
}

This works fine but the moment this button is pressed, the simulator starts using 5MB more of the memory. And when I press the back button on the navigation bar and than press the button that calls the newViewLoader method, 5MB more is taken by the simulator. And so on, every time the second view is loaded. So loading this view is quite expensive.

Isn't there some way to unload the view when the back button is pressed, so that memory doesn't keep going up every time the view is opened? Here's a screenshot with what happens every time the view is loaded.

Upvotes: 0

Views: 689

Answers (1)

Darren
Darren

Reputation: 10129

If you're not using ARC then you have at least one memory leak in your IBAction. It should be:

- (IBAction)newViewLoader:(id)sender {
    SecondViewController *secVC = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
    [self.navigationController pushViewController:secVC animated:YES];
    [secVC release];
}

or what I prefer:

- (IBAction)newViewLoader:(id)sender {
    SecondViewController *secVC = [[[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil] autorelease];
    [self.navigationController pushViewController:secVC animated:YES];
}

Otherwise you secVC is never released. You could try adding the release and see what happens.

However you really should be using ARC, which is Automatic Reference Counting. This takes care of the releases for you. Read up on it here: http://developer.apple.com/library/ios/#releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html

Upvotes: 2

Related Questions