1

I have seen it done both ways but I am not really sure what the difference is. Here is both scenarios:

Outside of fast enumeration loop:

NSDate *date;
for(date in array)
{
    //
}

Inside of fast enumeration loop:

for(NSDate *date in array)
{
    //
}

If I had to guess, the 2nd scenario would be more expensive on memory if it is creating a new NSDate pointer for every iteration of the loop? Or is that not what is happening?

user3451821
  • 123
  • 7

1 Answers1

4

There should be no difference in terms of cost, it's just a difference in scope.

With the pointer defined outside the loop it will continue to be defined after the loop has run (and would contain a pointer to the last item enumerated if you break out of the loop) so you could reuse it for something else.

With the pointer inside the loop, the pointer is not accessible outside the loop.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • 1
    If the pointer is defined outside the loop then it is set to `nil` after the loop has run, not to the last enumerated item (unless you `break` out of the loop). – Martin R Apr 29 '14 at 17:54
  • Thanks @MartinR, I didn't know that (never use externally defined variable) so thanks for the info (answer updated). – Wain Apr 29 '14 at 18:49
  • I am having trouble understanding why the pointer is set to nil after the loop (if it is declared outside and above the loop). Would that be because when doing fast enumeration, it is impossible to manipulate an object in the array, meaning in the end it would be nil (since it wasn't set to anything during the loop)? – user3451821 Apr 30 '14 at 04:30
  • An implementation detail of fast enumeration (compared to an explicit loop with counter). Not sure about documentation. – Wain Apr 30 '14 at 07:42