Re: Should I do loops in reverse order ?
Re: Should I do loops in reverse order ?
- Subject: Re: Should I do loops in reverse order ?
- From: Michael Rothwell <email@hidden>
- Date: Wed, 29 Nov 2006 20:25:52 -0500
On Nov 27, 2006, at 12:22 PM, Matt Neuburg wrote:
What I would do is:
int i,u=[myArray count];
for (i=0; i<u; i++)
However, I hope you realize that you aren't supposed to use a for-
loop at
all. You're supposed to use an NSEnumerator. :( m.
Interestingly, enumerators created for NSArray don't "see" changes
made to the array after the enumerator has been created. The output
of the block of code below is as follows; note that "two" is in the
output, but "MOOF" and "BADGER" are not.
2006-11-29 20:19:33.348 enum[11880] thisObject: one
2006-11-29 20:19:33.348 enum[11880] thisObject: two
2006-11-29 20:19:33.348 enum[11880] thisObject: three
2006-11-29 20:19:33.348 enum[11880] thisObject: four
2006-11-29 20:19:33.348 enum[11880] thisObject: five
NSMutableArray *myArray=[NSMutableArray array];
[myArray addObject:@"one"];
[myArray addObject:@"two"];
[myArray addObject:@"three"];
[myArray addObject:@"four"];
[myArray addObject:@"five"];
NSEnumerator * myArrayEnumerator = [myArray objectEnumerator];
[myArray addObject:@"MOOF"];
[myArray removeObjectAtIndex:2];
NSString *thisObject;
while (thisObject = [myArrayEnumerator nextObject])
{
NSLog(@"thisObject: %@", thisObject);
if ([thisObject isEqualToString:@"three"]) {
[myArray addObject:@"BADGER"];
}
}
Of course, I'm being bad. The documentation for NSArray says "When
this method (objectEnumerator) is used with mutable subclasses of
NSArray, your code shouldn’t modify the array during enumeration."
The documentation for NSEnumerator says "Note: It is not safe to
modify a mutable collection while enumerating through it. Some
enumerators may currently allow enumeration of a collection that is
modified, but this behavior is not guaranteed to be supported in the
future."
If you plan to mutate the array while looping through it, you
shouldn't use enumerators -- but that means you'll need to do
something more sophisticated than for (i=0; i<u; i++) ... by
adjusting u while in the loop, or something.
-M
_______________________________________________
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