My question is, when a for-loop is executed, does the compiler read it once, and then begin executing the loops with the values saved? Or does it evaluate the condition multiple times as the loop is executed? For example, say I have an NSMutableArray called myArray. My for loop looks something like this:
for (int i = 0; i < [myArray count]; i++){
[myArray addObject: object]; // this has maybe a 25% chance of happening
[myArray removeObjectAtIndex: whatever]; // also has a smaller chance of happening
What I want is, if an object is removed, for the condition to be reevaluated so the for loop doesn’t try to do anything with array objects that don’t exist, but I don’t want it to add to the count, because if it does the for loop will never end, as it will keep adding objects that add more objects, etc.
The condition in a for-loop will be evaluated each time through the loop. So adding to/removing from the NSMutable array will change how the condition is evaluated. Note that it doesn’t actually change the condition, just the results of evaluating it.
Note that if you are calling removeObjectAtIndex that you will need to adjust your index variable so that you don’t accidentally skip over an item (i.e. if you remove the item at the current index.)