iOS - 子视图控制器对父视图控制器具有“强”引用

Raf*_*afi 4 memory-leaks uiviewcontroller ios

我已经阅读了很多关于保留周期的内容。必要时,父级UIViewController应始终strong引用其子级,UIViewController而子级应始终weak引用其父级。

仅当他们相互引用时才这样吗?例如,如果父级UIViewController没有对其子级的任何引用,那么子级是否strong可以引用其父级UIViewController?从长远来看,我可以摆脱这种做法,还是在内存问题方面这是不好的做法?

小智 5

UIViewController.h.

/*
  If this view controller is a child of a containing view controller (e.g. a navigation controller or tab bar
  controller,) this is the containing view controller.  Note that as of 5.0 this no longer will return the
  presenting view controller.
*/
weak public var parentViewController: UIViewController? { get }
Run Code Online (Sandbox Code Playgroud)

// An array of children view controllers. This array does not include any presented view controllers.
@available(iOS 5.0, *)
public var childViewControllers: [UIViewController] { get }
Run Code Online (Sandbox Code Playgroud)

在这里您可以看到,parent 和 child 之间已经存在 strongandweak引用ViewControllers。您不应strong在从子项到父项的方向添加更多新引用,因为这会导致内存泄漏。