Search code examples
iphoneioscocoa-touchuiviewcontrolleruiapplicationdelegate

Memory leak in applicationWillEnterForeground


I am having around 9 ViewControllers in my application. I am opening the ViewControllers using the presentModalViewController. I want to display the 1st ViewController every time the user enters background and comes to foreground. If the user enters background in 8th ViewController and opens the application again , I need to display the 1st View Controller.

I am using the following code in the applicationWillEnterForeground

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    self.HomeScreenViewController = [[HomeScreenViewController alloc] initWithNibName:@"HomeScreenViewController" bundle:nil];
    self.window.rootViewController = _homeScreenViewController;
    [self.window makeKeyAndVisible];
}

and it is showing a memory leak. Obviously it will show the memory leak since I am initializing the HomeCtrl again, but I don't know how to fix it. Can anyone help me ?? I am not using the UINavigationController since the ViewControllers are pushed from right or Left side.


Solution

  • Change:

    self.HomeScreenViewController = [[HomeScreenViewController alloc] ....];
    

    to

    _HomeScreenViewController = [[HomeScreenViewController alloc] ....];
    

    Or you can do something like follow code:

    HomeScreenViewController *tempHSVC = [[HomeScreenViewController alloc] ....];
    self.HomeScreenViewController = tempHSVC;
    [tempHSVC release];
    self.window.rootViewController = self.HomeScreenViewController //or use just _homeScreenViewController;
    [self.window makeKeyAndVisible];
    

    And read some articles about memory management in objc.