0

我有一个weak实例变量持有UINavigationController.viewControllers堆栈中的视图控制器。弱引用被清零,但对象未被释放

我的变量自动变为nil,但视图控制器未被释放(因为UINavigationController拥有它)。

为什么我的弱引用被清零?

class NavController: SuperNavigationController 
{ 
    weak var weakViewController: UIViewController? 

    required override init() { 

     let rootViewController: UIViewController 

     if (/* whatever */) { 
      rootViewController = ViewController1(/*whatever*/) 
      weakViewController = rootViewController 
     } else { 
      /* whatever */ 
     } 

     /*** `weakViewController` is not `nil` at this point ***/ 

     /*** 
     *** This superclass function just does: 
     *** super.init(navBarClass:toolbarClass:) 
     *** viewControllers = [rootViewController] 
     ***/ 
     super.init(rootViewController: rootViewController) 
    } 

    // Without this, I get an "unimplemented initializer" exception 
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { 
     super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) 
    } 

... 
} 

但只要我去viewDidLoadweakViewControllernil,即使self.viewControllers.first仍然是完全相同的对象初始化,当我有。

有什么奇怪的方式UINavigationController拥有其viewControllers

编辑: 我设法识别和修复在浅层的原因(见我的回答如下),但我还是想知道为什么会这样。我会很乐意接受和赞扬一个答案,可以解释发生了什么!

+0

您不要在任何地方使用'rootViewController'。它在'init'结尾超出范围。因此,这个薄弱的参考资料不再指向任何事情。 – rmaddy

+0

我确实在代码中引用它;我的真实代码是UINavigationController的另一个子类的子类,它有一个'initWithRootViewController'函数。我将更新问题中的代码。感谢您指出了这一点。 – mrgrieves

回答

0

调用super.init()导致weak子类实例变量被设置为零。

我通过等待来设置weakViewController直到调用后super.init()

0

弱引用说,如果不出意外,在这指点,我并不需要它解决了这个问题。因此,如果拥有者是唯一拥有裁判并且比较弱的裁判,则弧线可以自由释放。

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html

+0

实际的对象由'UINavigationController'保留,因为它的'viewControllers'属性持有'rootViewController',这是'weakViewController'引用的同一个对象。由于实际的对象没有被取消分配,所以'weakViewController'将自己调零是没有意义的。 – mrgrieves

+0

使你的'''rootViewController'''变为零的机制是ARC没有看到任何强引用。是否有可能按值传递给UINavigationController(或你的子类链中的任何其他地方)?在你检查''''rootViewController'''为零之前,你的''''NavController'''对象是否可能被销毁? –

+0

好'rootViewController'是一个强大的参考; 'weakViewController'是弱实例变量。导航控制器超类在返回之前设置'UINavigationController.viewControllers'属性,所以'rootViewController'不会超出范围。 – mrgrieves

相关问题