• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Should I do loops in reverse order ?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Should I do loops in reverse order ?


  • Subject: Re: Should I do loops in reverse order ?
  • From: John Stiles <email@hidden>
  • Date: Mon, 27 Nov 2006 18:48:42 -0800

On Nov 27, 2006, at 6:40 PM, Jeff C wrote:

On Nov 27, 2006, at 12:45 PM, Sean McBride wrote:

On 2006-11-27 09:22, Matt Neuburg said:

What I would do is:

int i,u=[myArray count];
for (i=0; i<u; i++)

Be careful using this pattern if myArray is mutable and the contents are changing during iteration.


The value of u must be updated or you may run past the end of the array and get an exception.

I generally use the form


for ( i=0; i < [theArray count]; i++ )


when i'm not using NSEnumerator and hope that the implementer was smart enough to make the -count method as fast as possible.


Granted, that's probably not a good assumption if you're trying to squeeze every last cycle out of the machine, but for most of the applications I write, the sacrifice of performance is worth it to avoid bugs.

If you are mutating the array and inserting or removing elements inside the for loop, you may still have bugs even if you call -count each time.
For instance, if you delete the object at the current index inside the loop, you will skip over the next object in the array. Imagine i=2:


0: object A
1: object B
2: object C  <-- i == 2 so it references this object
3: object D
4: object E

And we delete object 2. Then on the next iteration through the loop, we have:

0: object A
1: object B
2: object D
3: object E <-- i == 3 so it references this object

Object D was never seen because the array contents shifted over.


_______________________________________________

Cocoa-dev mailing list (email@hidden)

Do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden


  • Follow-Ups:
    • Re: Should I do loops in reverse order ?
      • From: Jeff C <email@hidden>
References: 
 >Re: Should I do loops in reverse order ? (From: Matt Neuburg <email@hidden>)
 >Re: Should I do loops in reverse order ? (From: "Sean McBride" <email@hidden>)
 >Re: Should I do loops in reverse order ? (From: Jeff C <email@hidden>)

  • Prev by Date: Re: Should I do loops in reverse order ?
  • Next by Date: Re: Should I do loops in reverse order ?
  • Previous by thread: Re: Should I do loops in reverse order ?
  • Next by thread: Re: Should I do loops in reverse order ?
  • Index(es):
    • Date
    • Thread