iossubview

How to remove all subviews?


When my app gets back to its root view controller, in the viewDidAppear: method I need to remove all subviews.

How can I do this?


Solution

  • Edit: With thanks to cocoafan: This situation is muddled up by the fact that NSView and UIView handle things differently. For NSView (desktop Mac development only), you can simply use the following:

    [someNSView setSubviews:[NSArray array]];
    

    For UIView (iOS development only), you can safely use makeObjectsPerformSelector: because the subviews property will return a copy of the array of subviews:

    [[someUIView subviews]
     makeObjectsPerformSelector:@selector(removeFromSuperview)];
    

    Thank you to Tommy for pointing out that makeObjectsPerformSelector: appears to modify the subviews array while it is being enumerated (which it does for NSView, but not for UIView).

    Please see this SO question for more details.

    Note: Using either of these two methods will remove every view that your main view contains and release them, if they are not retained elsewhere. From Apple's documentation on removeFromSuperview:

    If the receiver’s superview is not nil, this method releases the receiver. If you plan to reuse the view, be sure to retain it before calling this method and be sure to release it as appropriate when you are done with it or after adding it to another view hierarchy.