I’m observing some strange behavior with a local variable within a nested for loop in objective-c.
The code below loops through an NSMutableArray called visitors that can range in size from 1 to 20.
I store a local copy of the object at position i and then I work out it’s bounding box.
I then loop through the array again within the first loop, picking out a second object from the list and working out it’s bounding box.
The collision check is almost never reached when the objects on screen over lap.
When I step through the code using the debugger I observe within the second for loop that once the variable visitor2 is set it never changes from that point on. It continues to point at the same object until the function call is complete.
All objects within the visitors array are definitely totally unique objects as in the same object isn’t added to the array twice I made sure to check for this.
I have no idea what could be causing this, I have never seen anything like it. Any help would be much appreciated.
Here is my code:
for (int i = 0; i < [visitors count]; i++)
{
// Obtain visitor from the list
Visitor* visitor1 = [visitors objectAtIndex: i];
// Calculate it's bounding box
CGRect visitor1rect = CGRectMake(visitor1.position.x - visitor1.size.x/2,
visitor1.position.y - visitor1.size.y/2,
visitor1.size.x, visitor1.size.y);
// Loop through all other visitors
for (int j = 0; j < [visitors count]; j++)
{
// Don't check for a collision with self
if (i != j)
{
// Obtain a visitor from the list
Visitor* visitor2 = [visitors objectAtIndex: j];
// Calculate it's bounding box
CGRect visitor2rect = CGRectMake(visitor2.position.x - visitor2.size.x/2,
visitor2.position.y - visitor2.size.y/2,
visitor2.size.x, visitor2.size.y);
// Chcek of the two bounding boxes intersect
if ( CGRectContainsRect(visitor1rect, visitor2rect) ) {
// Do stuff
}
}
}
}
Use
CGRectIntersectsRectfor your intersection test instead of “contains”, which means something different. If that fixes your problem, I’d guess that the debugger is just lying to you about the thingvisitor2points to– the code looks fine.