如何取消分配视图控制器?

时间:2017-02-28 21:03:45

标签: ios objective-c

我有一个登录屏幕,我在一个地方分配,而在另一个地方解雇,一旦解雇,它的dealloc方法永远不会被调用,持有登录屏幕的iVar即使在被指定为零之后仍然有一个值在我的解雇代码中。

这是我的分配

-(void)loginUser
    {
        loginScreen = [[LoginScreen alloc] initWithNibName:@"LoginScreen" bundle:nil];

        [self.tabBarController addChildViewController:loginScreen];
        [self.tabBarController.view addSubview:loginScreen.view];
        [loginScreen didMoveToParentViewController:self.tabBarController];
        [self.tabBarController.view bringSubviewToFront:loginScreen.view];
    }

这是我在另一种方法中的解雇和解除分配(无法解除分配)

        [UIView animateWithDuration:0.4 delay:0.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
             loginScreen.view.frame = CGRectOffset(frame, -1024, 0);
         }
                         completion:^(BOOL finished) {
                             // Remove the loginScreen
                             [loginScreen willMoveToParentViewController:nil];
                             [loginScreen.view removeFromSuperview];
                             [loginScreen removeFromParentViewController];
                             [loginScreen cleanupBeforeDealloc];
                             loginScreen = nil;
                         }];

我有一些代码可以在LoginScreen中监听键盘通知,但我在下面添加了一个方法来清理它,我尝试在上面的解雇代码中调用它,但是仍然没有解决它。 GRRRR。

-(void)cleanupBeforeDealloc
    {
        [self deregisterFromKeyboardNotifications];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }

1 个答案:

答案 0 :(得分:1)

我建议完全摆脱loginScreen。没有必要,因为这是一个子视图控制器,可以通过childViewControllers数组访问。 childViewControllers管理子视图控制器的保留和释放,并且您的loginScreen属性正在添加一个额外的保留,可能会搞乱。

但是,保留周期的实际原因可能是视图控制器已注册并保留了通知中心的观察者。这是保留周期的常见原因。通知中心保留观察员,观察员保留self。您无法在dealloc中取消注册以打破周期,因为保留意味着dealloc不会被调用。

相关问题