Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly manage memory stack and view controllers?

I'm really struggling with this basic iOS programming stuff but I just can't figure out whats happening and how to solve it.

I have my main Login controller that detects when a user is logged in and presents next controller if auth succeed:

@interface LoginViewController (){

    //Main root instance
    RootViewController *mainPlatformRootControler;
}

-(void)loggedInActionWithToken:(NSString *)token anonymous:(BOOL)isAnon{
    NSLog(@"User loged in.");

    mainPlatformRootControler = [self.storyboard instantiateViewControllerWithIdentifier:@"rootViewCOntrollerStoryIdentifier"];

    [self presentViewController:mainPlatformRootControler animated:YES completion:^{

    }];

}

And that works well, no problem.

My trouble is handling logout. How do I delete completely the RootViewController instance and show a new one?

I can see that RootViewController instances are stacking cause I have multiple observers and after a logout and then login they are called multiple times (as many times I exit and re-enter).

I've tried the following with no success:

First detecting logout in RootViewController and dismissing:

[self dismissViewControllerAnimated:YES completion:^{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"shouldLogOut" object:nil];

            }];

And then in LoginViewController:

-(void)shouldLogOut:(NSNotification *) not{
    NSLog(@"No user signed in");
    mainPlatformRootControler = NULL;
    mainPlatformRootControler = nil;
}

So how can I handle this? I know its a basic memory handle stuff but I just don't know how?

like image 509
Karlo A. López Avatar asked May 03 '18 17:05

Karlo A. López


1 Answers

First, you have to observe "shouldLogOut" in viewDidLoad should be like below:

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(shouldLogout:) name:@"shouldLogout" object:nil];

and after that in dismissViewControllerAnimated should be like below:

[self dismissViewControllerAnimated:true completion:^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"shouldLogOut" object:nil];
    }];

you need to define shouldLogOut: selector in login view controller

-(void)shouldLogOut:(NSNotification *) not{
    mainPlatformRootControler = nil;
}

Hope this will help you!

like image 194
MobileMatrix Avatar answered Sep 18 '22 16:09

MobileMatrix