Search code examples
iphoneiostagssubviews

Remove subviews with tags safely


This is not a real problem, i want just a clarification. I'm adding some subviews on a UIButton(each button has a tag), i know that there may be either 4 or 5 subviews. So, when i want to remove some subviews(specifically the 4th and 5th in this case):

int cnt=[[(UIView *)[self.scrollView viewWithTag:index] subviews] count];
  if (cnt==4) {
      [[[(UIView *)[self.scrollView viewWithTag:index] subviews] objectAtIndex:3] removeFromSuperview];
  }
  if (cnt==5) {
      [[[(UIView *)[self.scrollView viewWithTag:index] subviews] objectAtIndex:3] removeFromSuperview];
    //[[[(UIView *)[self.scrollView viewWithTag:index] subviews] objectAtIndex:4] removeFromSuperview]; <-- this crash
      [[[(UIView *)[self.scrollView viewWithTag:index] subviews] objectAtIndex:3] removeFromSuperview];

    }

The commented line can not be executed, of course, because there aren't more 5, but 4 subviews. So I have to remove the view pointing twice on the same index. I would like to know if it's a safe way to remove them, and i want to be sure that the last view is moved one position lower in the array [[self.scrollView viewWithTag:index] subviews].

Hope it is clear. Thanks


Solution

  • I'd rather use something like this:

    for(int i=cnt-1;i>=3;i--)
    {
      [[[(UIView *)[self.scrollView viewWithTag:index] subviews] objectAtIndex:i] removeFromSuperview];
    }
    

    Usually, when removing objects from lists, the safest method is to begin at the end. This way it doesn't even matter if they get reorganized.