Does a UIView retain its view controller

2019-07-24 14:02发布

Does a UIView retain it's associated view controller?

For example, in the following code the view is retained by the parent view. It would be handy if this view also retained its ViewController so that I could go ahead and release the controller in the loadView method.

- (void) loadView {

  ...

  MyViewController* ctrl = [[MyViewController alloc] init];
  [self.view addSubview: ctrl.view];
  [ctrl release];

}

The alternative, I suppose, is to keep track of the controller as an instance variable and release it when appropriate.

Thanks

2条回答
爷的心禁止访问
2楼-- · 2019-07-24 15:01

No it doesnt. You need a member variable, as you mentioned already.

(A view doesn't even know its own viewController)

查看更多
啃猪蹄的小仙女
3楼-- · 2019-07-24 15:02

You've got things somewhat backward: a view controller retains its view, not the other way around. Typically, one view controller manages the entire hierarchy of views that are on the screen together. While iOS 5 does allow you to use more than one view controller at a time, doing so correctly requires more than just adding one controller's view as a subview of another controller's view. For an easy to digest explanation of the process, read the preview of the View Controllers chapter of Matt Neuberg's book, Programming iOS 5, 2nd Edition. If you add one view controller as the child of another view controller, the parent will retain the child and you won't need to create a separate property for it. But do read the docs before you try it in order to avoid a lot of head scratching.

查看更多
登录 后发表回答