Properly release ViewController when adding subview without navigationController

1.7k views Asked by At

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?

3

There are 3 answers

0
seppo0010 On BEST ANSWER

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];
}

0
ySgPjx On

You could store a pointer to the view controller in an ivar and then release it in your dealloc method.

1
Kris Van Bael On

If such a subview has limited 'controlling needs', then you might consider to subclass from UIView and have the view control itself (e.g. Be its own delegate)

Otherwise you need to decide for the most logical 'owner' of these viewcontrollers (often the viewcontroller of the parentview) and make them ivars of their owner.