leo
leo

Reputation: 1011

How to release UITabBarController with all its view controllers?

I programmatically create a tab bar with two view controllers like the following code. I find it hard to clean the memory when I do not need the tab bar any more. Apple's documentation is very limited about releasing tab bar controller. I don't know how to release all the view controllers in the 'viewControllers' array. I tried to print out the retain count and found x & y's retainCount is as high as 5.

@interface X:UIViewController
@interface Y:UIViewController

@interface Z: UIViewController {
  UITabBarController *tabBar; 
}
@end

@implementation Z
-(IBAction)openTabBarUp{
  UITabBarController *tabBar = [[UITabBarController alloc] init];

  X *x = [[X alloc] init];
  Y *y = [[Y alloc] init];

  tabBar.viewControllers = [NSArray arrayWithObjects: x, y, nil];
  [self.view addSubView: tabBar.view];

}

this is how I try to release the memory:

-(IBAction)removeTabBar{
  [tabBar.view removeFromSuperView];
  [tabBar release];
  tabBar = nil;
}

Thanks

Leo

Upvotes: 0

Views: 1459

Answers (1)

visakh7
visakh7

Reputation: 26390

-(IBAction)openTabBarUp{
  tabBar = [[UITabBarController alloc] init];

  X *x = [[X alloc] init];
  Y *y = [[Y alloc] init];

  tabBar.viewControllers = [NSArray arrayWithObjects: x, y, nil];
  [self.view addSubView: tabBar.view];

}

You done need UITabBarController *tabBar = [[UITabBarController alloc] init]; in the openTabBarUp method as you already have an instance of it declared in the header file. You can release the tabBar using [tabBar release]; but Apple insists to add the tabBarController as the rootview of your main window and not as part of any view controller.

UPDATE

The Apple reference documents on UITabBarController states

When deploying a tab bar interface, you must install this view as the root of your window. Unlike other view controllers, a tab bar interface should never be installed as a child of another view controller.

Upvotes: 1

Related Questions