views:

77

answers:

1

I have been getting EXC_BAD_ACCESS on some devices in ad hoc beta for my app see here: http://stackoverflow.com/questions/2024266/help-debugging-iphone-app-excbadaccess

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?

+6  A: 

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.

benzado
Thanks, I'll try this out. Any idea if my old code could sometimes work ok on some devices and not on others? Are the problems I'm seeing only happening because the memory warning might have messed with what's released and what's not? Because the old code works fine on my device - of course that doesn't mean it's right :)
mac_55
Honestly, I *thought* Cocoa would throw a fail-fast exception for what the old code was doing. The EXC_BAD_ACCESS may be coming from somewhere else.
benzado
Hrm. Well I've changed this code, it's certainly not working any worse than before, but I need to do another ad hoc release to my friend to see if he's still getting the EXC_BAD_ACCESS. The old code definitely worked ok on my device before - in which case, naughty Cocoa. Thanks for the help. Looks like I'm out of ideas on the EXC_BAD_ACCESS then, since that's all that's in the magic method Terminal pointed me to
mac_55