Cocoa: Can't remove child view controller

Elias Atahi picture Elias Atahi · Feb 2, 2013 · Viewed 9.9k times · Source

I load the view of my main view controller. This main view controller then adds 2 child view controllers (split view: master and detail). When I log the number of child VCs right after adding them in the init method I get '2' as an output. When I then call the -switchToCommunication method and try to remove the detail child VC the view does not change. But the logs tell me that the array has actually shrunk from 2 child VCs to 1.

What's the matter?

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
[super init];

//add master view controller as childVC
self.test2 = [test2 new];
[self addChildViewController:self.test2];
self.test2.view.frame = CGRectMake(0, 0, 256, 768);
[self.view addSubview:self.test2.view];
[self.test2 didMoveToParentViewController:self];

//add detail view controller as childVC 
self.detail1Vc = [EADetailSupportViewController new];
[self addChildViewController: self.detail1Vc];
self.detail1Vc.view.frame = CGRectMake(284, 0, 740, 768);
[self.view addSubview: self.detail1Vc.view];
[self.detail1Vc didMoveToParentViewController:self];
NSLog(@"Child VC in childVC array: %d", [self.childViewControllers count]);



- (void) switchToCommunication {
//remove currently active detail view controller from parent view
NSLog(@"Child VC in childVC array: %d", [self.childViewControllers count]);


[[self.childViewControllers lastObject] willMoveToParentViewController:nil];
[[[self.childViewControllers lastObject] view] removeFromSuperview];
[[self.childViewControllers lastObject] removeFromParentViewController];

NSLog(@"Child VC in childVC array: %d", [self.childViewControllers count]);

NSLog(@"pushed");

//add communication detail view controller as child view controller
...
}

Answer

Gagan Joshi picture Gagan Joshi · Mar 20, 2014

This code may help you for removing child view, work fine for me.self.childViewControllers is an array so You can remove from a perticular index.

  [[self.childViewControllers objectAtIndex:0] removeFromParentViewController];