0

Under iOS 5, I encounter the following problem : the following code is called on a controller everytime a new product is picked in the application. It displays a bullet list of features in the controller's view.

Every bullet is an image that is added at the right place (in front of the corresponding text).

Now, the problem is that sometimes, apparently randomly, some bullets are not removed from the previous bullet lists, altough I remove it from its superview at the beginning of the methods.

  - (void) loadProduct{
    for (UIView * bullet in bullets){
        bullet.hidden = YES;
        [bullet removeFromSuperview];
    }
    [bullets removeAllObjects];
    [self.view setNeedsDisplay];


   ......here some stuff ......


    for (int i=0;i< numberOfFeatures;i++)
    {   

            UIImageView * bullet = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bullet.png"]];
            bullet.frame =CGRectMake(someFloatValue ,
                                     someOtherFloatValue,
                                     6,
                                     6);
            [self.view addSubview:bullet];

            [bullets addObject:bullet];
            [bullet release];

        }
    }

bullets is an NSMutableArray, a property of the controller.

Am I doing something wrong here?

madewulf
  • 1,870
  • 4
  • 26
  • 41
  • Your code seems fine. all the objects of bullets will be removed. When you some bullets are not removed, is it in the array or in display? – MadhavanRP Dec 30 '11 at 14:11
  • Thanks to babbidi, who hinted me about race conditions, I found the bug: the method was called twice almost simultaneously. – madewulf Dec 30 '11 at 14:27

1 Answers1

1

In bullets it seems that you're only storing the labels:

[bullets addObject:label];

So, when removing everything from bullets, you're only removing the labels from the superview, the bullets (UIImageView controls) are left there.

It might be easier if you create a custom control (a view holding both the bullet and the label) and use those instead

alex-i
  • 5,406
  • 2
  • 36
  • 56
  • You are totally right about the code that I initally posted, but this was just a mistake I made while simplifying the code to put in on SO. This error was not in the original code, and I edited it out of the code here. – madewulf Dec 30 '11 at 13:52
  • I see, everything seems ok now. Are you removing objects from `bullets` from any other place? Another possible issue could be race conditions (this, only if you're accessing `bullets` from multiple threads). – alex-i Dec 30 '11 at 14:04
  • Thanks a lot for your remark about race conditions! I just put a breakpoint in the method, and it appears that it was called twice almost simultaneously under some conditions. That probably explains it. Thanks a lot. That said, I will delete the question, since it does not make much sense as is. – madewulf Dec 30 '11 at 14:20