R – Overreleasing here

memory-managementobjective c

I have been getting EXC_BAD_ACCESS on some devices in ad hoc beta for my app see here:
Help debugging iPhone app – EXC_BAD_ACCESS

I have managed to use atos -arch armv6 -o myapp.app/myapp 0x000037a6
in terminal to track down the method that's causing this problem, and it's lead me to this piece of code:

for (UIView *view in scrollView.subviews) {
    [view removeFromSuperview];
}

I suspect that the app is receiving a memory access warning, and releasing the scrollview or UIImageViews which are it's children, so when I use that method above, it hits an error (and a crash), since it's overreleasing a view.

My question is, how can I make this safe, so that it's only released if it hasn't yet been released?

Best Answer

You are modifying an array while you iterate over it. It's subtle, but because removeFromSuperview removes it from the list of subviews, you are changing the array. Change your code to this,

NSArray *subviews = [scrollView.subviews copy];
for (UIView *view in subviews) {
    [view removeFromSuperview];
}
[subviews release];

and you should be fine.

Related Topic