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?

3
  • possible duplicate of iPhone - Remove all SubViews? Commented Jul 5, 2013 at 0:04
  • That's the most elegant way I know of. Commented Jul 5, 2013 at 0: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. Commented Jul 5, 2013 at 1:09

2 Answers 2

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: @[] ];
Sign up to request clarification or add additional context in comments.

Comments

0

This is an option

for (int i = self.subviews.count - 1; i >= 0; --i) {
    UIView* v = self.subviews[i];
    [v removeFromSuperview];
}

1 Comment

Thank you for your answer. I suppose I was looking for something a bit more elegant, but I assume this works just as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.