0
for(UIView *view in [_scrollView subviews]) {
    NSMutableArray *_mutableArray = [_array mutableCopy];
    [_mutableArray filterUsingPredicate:[NSPredicate predicateWithFormat:@"guid like %@",view.object.guid]];
    if([_mutableArray count] != 0) {
        //object is already on screen we need to update it
        [view setObject:(Object*)[_mutableArray objectAtIndex:0]];
    }
    else {
        //object not on screen add it 
         _mutableArray = [_array mutableCopy];
        [_mutableArray filterUsingPredicate:[NSPredicate predicateWithFormat:@"guid not like %@",view.object.guid]];

        UIView *newView = [[UIView alloc] initWithObject:(Object*)[_mutableArray objectAtIndex:0]];
        [_scrollView addSubview:newView];

    }
}

As you can see this method updates the objects that are on screen and if an object is not on screen it is created and added to the scrollView subview hierarchy. Now my concern is that I'm modifying the scrollView subviews hierarchy while enumerating it. Will this crash my app eventually?

If yes, how can I modify the above code to be safe and achieve the same functionality?

Thanks!

Horatiu Paraschiv
  • 1,750
  • 2
  • 15
  • 37

1 Answers1

0

Will this crash my app eventually?

Perhaps. The answer in this particular case would be in how UIScrollView returns its list of subviews. If it makes a copy or a new array from it's list of subviews and returns that, then no, it won't crash. If it returns the same array it'll later update when you addSubview:, then you're playing with fire.

Unless it's documented otherwise, mutating a collection you're enumerating is a bad idea. Make a copy of it first and enumerate that instead.

MyztikJenz
  • 1,650
  • 14
  • 19
  • 3
    [UIView](https://developer.apple.com/library/ios/#documentation/uikit/reference/UIView_Class/UIView/UIView.html#//apple_ref/occ/cl/UIView) declares `@property(nonatomic, readonly, copy) NSArray *subviews` – Paul.s Feb 09 '12 at 22:47
  • Good point... then enumerating `subviews` shouldn't have any ill effects. Having using AppKit/NSView for so long I'm just used to making copies before mutating. – MyztikJenz Feb 09 '12 at 22:50
  • Thanks to both of you, so I'm safe in this case. – Horatiu Paraschiv Feb 09 '12 at 23:22