Search code examples
iphoneobjective-ciosuiviewcontrollerretaincount

Properly release ViewController when adding subview without navigationController


Something I run into a lot is not being able to create and destroy a ViewController properly when adding the ViewController.view as a subview not on a navigation controller.

for example:

MyViewController *myViewController = [[MyViewController alloc] init];  
[currentView addSubView:myViewController.view];  
[myViewController release];

That Works great if it is a controllerless view and there are no UIControls that the user must interact with. But sending messages to the view controller of that view causes EXEC_BAD_ACCESS because they are no longer in memory.

MyViewController *myViewController = [[MyViewController alloc] init];  
[currentView addSubView:myViewController.view]; 

This works when sending messages, however it is a memory leak and is caught by the static analyzer.

Setting it as a property of the current view controller works sometimes. But if I need to create a bunch with an unknown number of MyViewControllers and add them to something like a UIScrollView, that doesn't work either.

for (int i = 0; i < [myViewControllers count]; i++) {  
    MyViewController *myTmpViewController = [[MyViewController alloc] init];
    [myCurrentUIScrollView addSubview:myTmpViewController.view];
    [myTmpViewController release];
}

Still gonna crash if myTmpViewController has user interaction or something similar. How does one go about adding this, and releasing it properly?


Solution

  • You can have a NSMutableArray and add the controllers there.

    
    for (int i = 0; i < [myViewControllers count]; i++) {  
        MyViewController *myTmpViewController = [[MyViewController alloc] init];
        [myCurrentUIScrollView addSubview:myTmpViewController.view];
        [myControllers addObject:myTmpViewController];
        [myTmpViewController release];
    }
    
    // ..
    
    - (void) dealloc {
        [super dealloc];
        [myControllers release];
    }