iosuiviewuiviewcontroller

iOS: Does an UIView hold an reference to its UIViewController?


By default, UIView returns its UIViewController in nextResponder function - if it has one. I think UIView must have hold an reference to the UIViewController.

If so, won't it lead to a circular reference between them, since UIViewController also holds an reference to UIView?

--- update -----------

I notice that the UIView has an private member named _viewDelegate, which is the UIViewController. Anyone knows how this is assigned?

enter image description here

--- update -----------

I found that when the view is loaded and assigned to the view controller, its _viewDelegate property points to the view controller at the same time. So this probably happens in the didSet event of view property.

According to the name of property _viewDelegate, it should be a delegate, which normally is a weak reference, I guess.


Solution

  • Does an UIView hold an reference to its UIViewController?

    A UIView might or might not hold a reference to a UIViewController, but this is an internal implementation detail. It is not documented, and should not be relied upon.

    If so, won't it lead to a circular reference between them, since UIViewController also holds an reference to UIView?

    This is a circular reference in the simplest sense, but that is not necessarily a strong reference cycle or retain cycle. That is, the internal reference could be weak or unsafe_unretained or manually set to nil at the appropriate time.

    There might not always be a stored reference, though. Code like this can traverse the responder chain and find the closest view controller:

    // self is the view
    
    UIResponder *responder = self;
    while ((responder = [responder nextResponder])) {
        if ([responder isKindOfClass:UIViewController.class]) break;
    }
    return (UIViewController *)responder;
    

    (Code from UIView+PSPDFKitAdditions.m.)

    The references you're seeing might be loaded lazily, or just be temporary cached values.