Question

In the app im creating there are many pages that look mostly the same with some part which is different. To handle this kind of situation i created a container controller that contains a subview. I want this subview to be filled by the contents of another controller (and its associated nib) which i will created dynamically as needed based on context.

I have the following method somewhere

- (void) someAction {
    UIViewController* contentController = [[MyContentController alloc] init];
    UIViewController* containerController = [[MyContainerController alloc] initWithContentController:contentController];
    [navigationController pushViewController:pageController animated:YES];
    [contentController release];
    [containerController release];
}

In MyContainerController.m i retain the controller in a property

- (id)initWithContentController:(UIViewController *)aContentController {
    if ((self = [super initWithNibName:@"MyContainerController" bundle:nil])) {
        contentController = aContentController;
    }
    return self;
}

Later in viewDidLoad i do the following

- (void)viewDidLoad {
    [super viewDidLoad];
    [contentViewContainer addSubview:contentController.view];
}

contentViewContainer is the view that's supposed to hold the page specific info. Unfortunatly this fails with EXC_BAD_ACCESS. The funny thing is that if i alloc and init the content controller from within viewDidLoad everything works. It seems that i cant pass a contoller i allocated from another place. Can anyone assist.

Was it helpful?

Solution

Since you are releasing contentController in the actionMethod you have to retain contentController in you init method

- (id)initWithContentController:(UIViewController *)aContentController {
    if ((self = [super initWithNibName:@"MyContainerController" bundle:nil])) {

        contentController = [aContentController retain];
    }
    return self;
}

But, why do you need this? Controllers are supposed to control views and no other controllers. If you think you really need that then you want to use UINavigationController or UITabBarController maybe. You can also load views without a controller (see here)

I personally think that having UIViewControllers inside of simple UIViewController is not a preferable approach

Hope it helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top