OneChillDude
OneChillDude

Reputation: 8006

Difference between these two for loops in objective c

Ok, so I'm building an iOS game, and I feel like I have a pretty good grasp on objective-c, but one thing that caused me a ton of pain was the reference-errors I got when I used the following for-loop

for (MyObject *object in nsMutableArrayOfObjects) {
    // do things with object
}

vs.

for (int i = 0; i< nsMutableArrayOfObjects.count; i++) {
    // do things with nsMutableArrayOfObjects[i];
}

I had a few of these (first loop example) running in sequence and I kept getting the EXC_BAD_ACCESS error. I also had some loop nesting, where I would put on inside the other. I'm just really curious to know what the key differences are. I'm assuming the differences have something to do with how they reference the objects in the array.

Upvotes: 2

Views: 494

Answers (3)

alexhajdu
alexhajdu

Reputation: 400

Both of cycles are correct, we can't answer as we don't see more code... Anyway, with EXC_BAD_ACCESS you are probably accessing deallocated object.

Upvotes: -1

Jono
Jono

Reputation: 171

Maybe it has something to do with memory allocation as nsMutableArrayOfObjects is not creating a new pointer in the loop for every Clock cycle, whereas your first loop allocates a new pointer in each Cycle

Beats a wild guess

Upvotes: 0

Thomas Zoechling
Thomas Zoechling

Reputation: 34253

The first example you posted uses Fast Enumeration - The preferred method to enumerate collections.
Apple provides the details in the Collections Programming Guide.

I am not sure what caused the EXC_BAD_ACCESS in your case (sounds more like a memory management issue). But one thing to keep in mind when using fast enumeration is, that you can't mutate the collection you are enumerating.

Upvotes: 2

Related Questions