Frequent visitor but first post here on StackOverflow, I’m hoping that you guys might be able to help me out with this. I’m fairly new to Obj-C and XCode, and I’m faced with this really… weird… problem. Googling hasn’t turned up anything whatsoever. Basically, I get an EXC_BAD_ACCESS signal on a line that doesn’t do any dereferencing or anything like that that I can see. Wondering if you guys have any idea where to look for this. I’ve found a work around, but no idea why this works… The line the broken version barfs out on is the line:
LevelEntity *le = entity;
where I get my bad access signal.
Here goes:
THIS VERSION WORKS
NSArray *contacts = [self.body getContacts];
for (PhysicsContact *contact in contacts)
{
PhysicsBody *otherBody;
if (contact.bodyA == self.body)
{
otherBody = contact.bodyB;
}
if (contact.bodyB == self.body)
{
otherBody = contact.bodyA;
}
id entity = [otherBody userData];
if (entity != nil)
{
LevelEntity *le = entity;
CGPoint point = [contact contactPointOnBody:otherBody];
}
}
THIS VERSION DOESNT WORK
NSArray *contacts = [self.body getContacts];
for (NSUInteger i = 0; i < [contacts count]; i++)
{
PhysicsContact *contact = [contacts objectAtIndex:i];
PhysicsBody *otherBody;
if (contact.bodyA == self.body)
{
otherBody = contact.bodyB;
}
if (contact.bodyB == self.body)
{
otherBody = contact.bodyA;
}
id entity = [otherBody userData];
if (entity != nil)
{
LevelEntity *le = entity;
CGPoint point = [contact contactPointOnBody:otherBody];
}
}
Here, the only difference between the two examples is the way I enumerate through my array. In the first version (which works) I use for (… in …), where as in the second I use for (…; …; …). As far as I can see, these should be the same.
This is seriously weirding me out. Anyone have any similar experience or idea whats going on here? Would be really great 🙂
Cheers,
Alex
First, if you have a crash, you have a backtrace. Always provide the backtrace with your question (it’ll be in the debugger and can be copy/pasted).
As Vojito implied, the most common cause of crashes like these is related to the over-releasing of objects.
In your case,
for(;;)andfor(... in ...)are not actually exactly the same. The latter is very likely causing the objects within the array to be retained for the duration of iteration or autoreleased upon retrieval (I say “very likely” because I didn’t test it — but it would explain the behavior).In your code, you are modifying your object graph during iteration with statements like
otherBody = contact.bodyB. If any one of those statements happens to cause one of the items in the array being iterated to be released out from under the array, you would see a crash. Similarly, if the modification of the object graph causes eithercontact.bodyAorcontact.bodyBto become a dangling reference, you would see a crash.All just an educated guess. Post the backtrace and, as Vojito suggested, run under the Allocation instrument in Instruments with zombie detection enabled.