user3521174
user3521174

Reputation: 33

how to switch views and deallocate previous view's memory

I have an app with several views, each view is its own view controller. I am switching views by using the following method.

TableViewSelect *tableview = [[TableViewSelect alloc] initWithNibName:nil bundle:nil];
[self presentViewController: tableview animated:YES completion:NULL];

I have been told in another question that this would cause the new view to be displayed over the previous view but without deallocating the memory. So as user flips though views, the memory is always growing. i.e. Memory leak. Can anyone tell me how to switch views where the memory is deallocated when leaving the view.

Thanks

Upvotes: 1

Views: 426

Answers (2)

staticVoidMan
staticVoidMan

Reputation: 20274

At some point, it would be advisable to do:

//in TableViewSelect class on some action
[self dismissViewControllerAnimated:YES completion:nil];

Plus... depending on your flow, but say you have the following classes:

  1. AppDelegate
  2. ViewController
  3. FirstVC
  4. SecondVC
  5. ThirdVC

Say:

  • AppDelegate's rootViewController is ViewController
  • ViewController presents FirstVC
  • FirstVC presents SecondVC

So now... you're on SecondVC and need to show FirstVC again, then in this case, to conserve memory, you'll need to dismiss SecondVC.

But... if you've something even remotely like:

  • FirstVC -> SecondVC -> ThirdVC (back to) -> FirstVC

then you're better off with a UINavigationController because this seems like a potential memory hog.

Upvotes: 1

CrimsonChris
CrimsonChris

Reputation: 4651

If you only want to display one view at a time, you could do something like this...

 @property (nonatomic, strong) UIVIewController *currentViewController;

- (void)presentViewController:(UIViewController *)viewControllerToPresent animated:    (BOOL)animated completion:(void (^)(void))completion {
        if (self.currentViewController != nil) {
            [self.currentViewController dismissViewControllerAnimated:animated completion:^{
                self.currentViewController = viewControllerToPresent;
                [super presentViewController:viewControllerToPresent animated:animated completion:completion];
            }];
        } else {
            self.currentViewController = viewControllerToPresent;
            [super presentViewController:viewControllerToPresent animated:animated completion:completion];
        }
}

Upvotes: 0

Related Questions