开发者

objective-c addSubView retain count

开发者 https://www.devze.com 2023-01-13 21:59 出处:网络
I was under the impression that adding a subview to a view goes like this: UITableVi开发者_如何学PythonewController *sitesel = [[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];

I was under the impression that adding a subview to a view goes like this:

UITableVi开发者_如何学PythonewController *sitesel = [[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];
sitesel.view.frame = CGRectMake(0,0,100,100);
[self.left addSubview:sitesel.view];
[sitesel release];

But it seems I should not release the sitesel (the controller)? So should I release the view or what, I had this retain stuff nailed a while ago, but it's slipped. (And to use a TableView, you have to subclass UITableViewController right?)

(self.left is a subview of self.view, added in a nib)


addSubview does retain the view, that's not the problem. Your issue is that the controller for the view goes away a little later.

You shouldn't release the view, because that's none of your business. You didn't create it, you didn't touch it. Leave it alone.

In order to keep things working, it needs to stay connected to a valid controller. Hence, you must not release the controller, but keep it around. Add a property like @property(retain) UITableViewController *siteController; and then do self.siteController = sitesel; before you release the controller. This way everything stays in memory.

PS: For cleanness, you should probably change the view in the accessor for sitesel. Just to make sure it always comes and goes along the controller. Your method would then get even shorter, just setting the controller.

ADDED: That setter could look like that, requiring you to set only the controller and the view being updated transparently:

- (void)setSiteselController:(UITableViewController *)ctrl {
  if (_sitesel)
    [_sitesel.view removeFromSuperview];

  [_sitesel autorelease];
  _sitesel = [ctrl retain];

  if (_sitesel) {
    _sitesel.view.frame = CGRectMake(0,0,100,100);
    [self.left addSubview: _sitesel.view];
  }
}

Your original code will then shrink to this much cleaner version:

UITableViewController *sitesel = [[UITableViewController alloc] initWithStyle: UITableViewStyleGrouped];
self.siteselController = sitesel;
[sitesel release];

PPS: You don need an controller for a UITableView to work. It's just much simpler!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号