ios - 如何正确管理内存堆栈和视图控制器?
问题描述
我真的在为这个基本的 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;
}
那么我该如何处理呢?我知道它是一个基本的内存句柄,但我不知道怎么做?
解决方案
首先,您必须观察 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;
}
希望对你有帮助!
推荐阅读
- sql - T-SQL - 传入 ID 列表以创建 ID 关系表到新记录
- flutter - Flutter,如何将参数传递给构造函数
- java - 使用模拟 2 功能和相同的答案
- http - 如何仅使用 ssh 连接(无 cURL 或其他实用程序)手动 POST JSON 数据
- javascript - 如何合并对象数组中的值
- javascript - 如何在 admin-bro 中配置存储桶以本地存储上传的文件
- swift - Firebase Analytics - 记录 screen_view 在 SwiftUI 中不起作用
- sql - SQL Server 中带有 JOIN 的 UPDATE 语句未按预期工作
- r - 如何计算 r 中每组的平均变化?
- laravel - 如何验证来自 Laravel 中父控制器的相关对象请求数据?