views:

29

answers:

2

I have an app that programmatically creates labels and text fields based on the contents of a text file. Whenever the view controller is loaded, it creates text fields and labels that are different each time. My problem is I need to clear out the labels and text fields without releasing the view controller since I need to keep track of the view controller. I tried self.viewController = nil, but I'm pretty sure this results in a memory leak. Is there a way to delete all the subviews of a view?

A: 

If you have a view named view, you should be able to remove all of the subviews from the view using this code:

for (UIView *subview in view) {
    [subview removeFromSuperview];
}
GregInYEG
+1  A: 

What Greg meant to say is this:

for (UIView *subview in self.view.subviews) {
    [subview removeFromSuperview];
}

This may not work as you would expect though, as Objective C doesn't like it when you modify an array while you're iterating through it in a for loop. A safer choice would be this:

while ([self.view.subviews count] > 0) { 
    [[self.view.subviews lastObject] removeFromSuperview]; 
}
cduhn