1

Forgive me if this has been asked, and I did not perform a good enough search on SO.

I am doing the following to enumerate over an array of subviews, while removing each subview from its superview:

for( NSView *subview in [[self subviews] copy])
{
    [subview removeFromSuperview];
}

It works fine, but is there a more appropriate way to implement this loop, rather than simply copying the array?

wh1tney
  • 1,157
  • 1
  • 9
  • 16
  • possible duplicate of [iPhone - Remove all SubViews?](http://stackoverflow.com/questions/2156015/iphone-remove-all-subviews) – Danilo Jul 05 '13 at 00:04
  • That's the most elegant way I know of. – The Kraken Jul 05 '13 at 00:05
  • @Danilo I suppose I am asking for the best approach to the solution for that question. I had a working solution, I was wondering the preferred/more correct way to do it. – wh1tney Jul 05 '13 at 01:09

2 Answers2

2

NSView's subviews getter directly returns it's mutable array without copying it. So if you want to remove specific subviews the way of doing it is to copy it. Otherwise in your specific case, since you want to remove all subviews, you can just set it's subviews to be an empty array:

[self setSubviews: @[] ];
Roshan
  • 1,937
  • 1
  • 13
  • 25
Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187
0

This is an option

for (int i = self.subviews.count - 1; i >= 0; --i) {
    UIView* v = self.subviews[i];
    [v removeFromSuperview];
}
Khanh Nguyen
  • 11,112
  • 10
  • 52
  • 65
  • Thank you for your answer. I suppose I was looking for something a bit more elegant, but I assume this works just as well. – wh1tney Jul 05 '13 at 01:05