开发者

Properly releasing UITableViewController and UITableView directly added to a UIViewController

I have a UIViewController (parentVC) to which I add a UITableViewController as follows (it is not pushed since the tableview only occupies about hal开发者_JAVA百科f the screen):

tableVC = [[SmallTableVC alloc] initWithStyle:UITableViewStylePlain];
          [self.view addSubview:tableVC.tableView];

In dealloc, I add [tableVC release];

Using instruments, I can see that the tableVC is indeed fully released when parentVC released, which is good, but I am not sure why as I thought that the UITableView of tableVC would have a retain count of 2 (1 for retention by tableVC and 1 for retention by parentVC). My intuition was that an additional [tableVC.tableView release] would be required, but adding it crashes the app. Why is tableVC released properly by the current code (if indeed it actually is)? Does a UITableViewController not retain its tableView? Thanks.


You are allocating tableVC, so retain count is 1. You do not pass tableVC to anything else, so there is no reason anything else would retain it. If something else did retain tableVC, it would be responsible for releasing it when it no longer needed it.

If you were to look at the retain count of the UITableView owned by tableVC it might be higher than one, as it is retained by both tableVC and, after you call addSubview, the view owned by parentVC.

Edit:

If you want to forcibly clean up tableVC.tableView then call removeFromSuperview before releasing tableVC. I believe that view controllers implicitly do this when released, but it does not hurt to do it manually as well.

After you call [self.view addSubview:tableVC.tableView] tableVC.tableView will have a retain count of at least two. One for the view hierarchy and one for tableVC. When you release tableVC it is removing the tableView from the view hierarchy which releases tableView, then it is releasing tableView itself. Even if it was not removing tableView from the view hierarchy, parentVC.view is about to be torn down and release the view hierarchy that included tableVC.tableView.

Only release what you have explicitly retained. The naming conventions make this pretty clear. If the name includes retain, new, alloc or copy then you should release the result.


Be careful trusting retain counts on iPhone. iPhone does not do real garbage collection and therefore these values should be ignored. Follow the memory management rules and you will be fine.

In this case, the tableVC will be released in "dealloc" and the view it controlled will be released in [super dealloc].

Do not trust retain counts!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜