Does UIView's addSubview really retain the view?

后端 未结 3 1294
时光取名叫无心
时光取名叫无心 2020-12-08 09:09

I ran into a situation that seems to suggest otherwise. In the following code snippet, if I remove the line: self.navigationController = nav, the root controller\'s view wo

相关标签:
3条回答
  • 2020-12-08 09:38

    This line:

    [window addSubview:nav.view];
    

    does NOT add a view to the screen immediately. It is displayed by the OS in some future run loop on a possibly different thread. The actual implementation we can't be sure of.

    This is why Apple defines delegate methods like viewDidAppear/viewWillAppear, otherwise we would not need them as we would know precisely when these events occur.

    Moreover, adding a subview as you said, does indeed retains the view. It does NOT however retain the view controller or the navigation controller. Since the navigation controller WILL retain any added view controllers, we do not have to back them with an ivar.

    But, your reference to the navigation controller must persist beyond the scope of the method. or depending on your code it could be dealloc-ed or have its reference lost.

    So you must keep a reference to the navigation controller with an ivar and set it like so:

    self.navigationController = nav; 
    

    So even though nav.view contains a pointer to testViewController.view, the application has no reference the navigation controller and, by extension, the view. The result is a blank screen.


    To make this more obvious that it isn't a retain/release problem, you are actually leaking in the following method:

    self.testViewController = [[TestViewController alloc] initWithNibName:@"TestView" bundle: [NSBundle mainBundle]];
    

    You need to autorelease to balance out your retain/releases by:

    self.testViewController = [[[TestViewController alloc] initWithNibName:@"TestView" bundle: [NSBundle mainBundle]] autorelease];
    

    So, that means your view has never, ever been deallocated any time you have ran this code. Which further assures us that your issue is indeed a lost reference.

    0 讨论(0)
  • 2020-12-08 09:42

    The problem probably isn't that the view isn't retained, it's that the controller isn't retained.

    Without this line:

    self.navigationController = nav
    

    Nothing is retaining the navigation controller. It would be strange to have the view outlive the controller.

    0 讨论(0)
  • 2020-12-08 09:46

    This doesn't look lika a retain/release question to me. You view won't show up if you comment out self.navigationController = nav; because then in the next line, [window addSubview:self.navigationController.view] your self.navigationController property won't be set. It's probably nil or it would crash but can't say for sure without more of the code.

    0 讨论(0)
提交回复
热议问题