Search code examples
iosobjective-cmemory-leaksuistoryboardsegue

XCode: Memory Leak When Performing Modal Segue


When a logged in user opens my application, they are sent to the main TabBarController from my AppDelegate, like so:

UITabBarController *tabBar = (UITabBarController *)self.window.rootViewController;
tabBar.selectedIndex = 2; 
// (this is MainViewController in the tab bar)

Now, the user is in MainViewController. When the user selects a particular chat they'd like to enter, they are sent to the ChatViewController (not on the TabBarController), like so:

[self performSegueWithIdentifier:@"showChatSeg" sender:self];

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.destinationViewController isKindOfClass:ChatViewController.class]){
        ChatViewController *destinationViewController = (ChatViewController *)segue.destinationViewController;

        if(self.createdDialog != nil){
            destinationViewController.dialog = self.createdDialog;
            self.createdDialog = nil;
        }else{
            QBChatDialog *dialog = [ChatService shared].dialogs[self.selectedChat];
            destinationViewController.dialog = dialog;
        }
    }
}

When this happens, I see a spike in memory usage, which makes sense. However, when the user leaves the ChatViewController and return to the MainViewController, like so:

- (IBAction)backButton:(id)sender {  
    [self performSegueWithIdentifier:@"fromChatToDashSeg" sender:nil];   

// This is a storyboard segue back to the MainTabBarController

}

I get the following warning:

Attempt to present <MainTabBarController: 0x17ef28d0> on <ChatViewController: 0x17d6c940> whose view is not in the window hierarchy!

And the memory usage remains the same. And when the user enters a chat again, the memory continues to increase. Am I not dismissing the sending view controllers properly?


Solution

  • What you are doing is not going "back" but rather, you are presenting a copy of the previous view on top of the one you already have. That's why memory is building up, because you just keep stacking more and more views on top of eachother. Assuming you are using a modal segue to present your chat view, try calling:

    [self dismissViewControllerAnimated:YES completion:nil];