开发者

Safe to release UINavigationController?

I am creating a (UIPopoverController) popover controller and (UINavigationController) navigation controller for the popover, where both controllers are declared in the header file. Then, when they are created:

myNavController = [[UINavigationController alloc] initWithRootViewController:[[[MyPopoverControllerClass alloc] initWithNibName:@"MyPopoverNib" bundle:[NSBundle mainBundle]]autorelease]];

myPopoverController = [[UIPopoverController alloc] initWithContentViewController:开发者_运维知识库myNavController];

At this point, is it safe to release myNavController?


You may release your navigation controller after initializing your popover controller if this class isn't going to refer to it again.


If myNavController is an instance variable, then you shouldn't release it until your dealloc method. If it's just a local variable, you should release it after the last reference to it in that method.


Just think about Object Ownership and Disposal convention which briefly says that if you've alloc'ed an object, you are its owner.

In other words, you are in all rights to release myNavController as soon as you don't need it.

From another side, UIPopoverController should take ownership over myNavController using retain.

So, (again) yes. You can safely release myNavController.

There are some rare situations when ownership convention rules not respected. These kind of exceptions are mentioned in documentation for specific methods. But here is not the case.

Lets apply these rules for your snippet: In the first line

  myNavController = [[UINavigationController alloc] initWithRootViewController:[[[MyPopoverControllerClass alloc] initWithNibName:@"MyPopoverNib" bundle:[NSBundle mainBundle]]autorelease]];

retain count for myNavController is at least 1.

The second line

myPopoverController = [[UIPopoverController alloc] initWithContentViewController:myNavController];

will result in retain count for myNavController to be at least 2, through ownership taken inside initWithContentViewController.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜