Alex
Alex

Reputation: 15

removefromsuperview just gives error

I have a paginating scrollview with UIImageView's inside. At a point i need to remove some Imageviews to avoid memory-problems.

But at any point i just get a BAD_ACCESS .

for(UIView *subview in [scrollView subviews]) {
  if([subview isKindOfClass:[UIImageView class]]) {
   if ( ([subview tag] != ActualPage) && ([subview tag] != (ActualPage - 1)) && ([subview tag] != (ActualPage+1)) )
   {
       [subview removeFromSuperview];
   }
  } 
}

Basically i wanna remove every subview except the actual page, one back and one forward.

Upvotes: 1

Views: 860

Answers (3)

Looks like you might have to read http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocFastEnumeration.html “… Enumeration is “safe”—the enumerator has a mutation guard so that if you attempt to modify the collection during enumeration, an exception is raised.”

Greetings

Upvotes: 0

Michael Kessler
Michael Kessler

Reputation: 14235

It isn't a good practice to remove objects from the array that you are looping over.

Try to add all the views that you want to remove from the scroll view to another array and then go over all the items in that array and apply the removeFromSuperView on them.

You can even use the makeObjectsPerformSelector instead of going over the new array...

EDIT:
Code sample:

NSMutableArray *viewsToRemove = [NSMutableArray array];
for (UIView *subview in [scrollView subviews]) {
    if ([subview isKindOfClass:[UIImageView class]]) {
        if ( ([subview tag] != ActualPage) && ([subview tag] != (ActualPage - 1)) && ([subview tag] != (ActualPage+1)) ) {
            [viewsToRemove addObject:subview];
        }
    } 
}
[viewsToRemove makeObjectsPerformSelector:@selector(removeFromSuperView)];

Upvotes: 1

bbum
bbum

Reputation: 162712

When you have a crash, it is helpful to post the backtrace. Is the crash happening in that loop or elsewhere?

If that loop is executing during display, then you are violating the contract of -removeFromSuperview which explicitly states that it should not be called in the middle of display.

I could also imagine a crash related to causing the subviews to mutate in the middle of enumeration.

Without a backtrace, it is impossible to say conclusively.

In general, if you have code that is using isKindOfClass: for behavior such as this, you have a design oddity that ought to be revisited.

Upvotes: 0

Related Questions