Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Should I do loops in reverse order ?




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:
http://lists.apple.com/mailman/options/cocoa-dev/email@hidden

This email sent to email@hidden
References: 
 >Re: Should I do loops in reverse order ? (From: Matt Neuburg <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.