首页 > 解决方案 > 如何正确管理内存堆栈和视图控制器?

问题描述

我真的在为这个基本的 iOS 编程东西苦苦挣扎,但我就是不知道发生了什么以及如何解决它。

我有我的主登录控制器,它检测用户何时登录并在身份验证成功时显示下一个控制器:

@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:^{

    }];

}

而且效果很好,没问题。

我的麻烦是处理注销。如何完全删除 RootViewController 实例并显示一个新实例?

我可以看到 RootViewController 实例正在堆叠,因为我有多个观察者,并且在注销然后登录后它们被多次调用(就像我退出并重新进入的次数一样)。

我尝试了以下但没有成功:

首先在 RootViewController 中检测注销并关闭:

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

            }];

然后在 LoginViewController 中:

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

那么我该如何处理呢?我知道它是一个基本的内存句柄,但我不知道怎么做?

标签: iosobjective-cmemory-managementviewcontroller

解决方案


首先,您必须观察 viewDidLoad 中的“shouldLogOut”应该如下所示:

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

然后在dismissViewControllerAnimated中应该如下所示:

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

您需要在登录视图控制器中定义 shouldLogOut: 选择器

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

希望对你有帮助!


推荐阅读