Re: Style Advice for using NSEnumerator
Re: Style Advice for using NSEnumerator
- Subject: Re: Style Advice for using NSEnumerator
- From: Quincey Morris <email@hidden>
- Date: Mon, 17 May 2010 12:57:14 -0700
On May 17, 2010, at 06:32, Carlton Gibson wrote:
> // Set up the stroke colors (and the variables for enumeration)
> NSArray *strokeColors = [NSArray arrayWithObjects:
> @"redColor", @"orangeColor", @"yellowColor", @"greenColor",
> @"blueColor", @"cyanColor", @"magentaColor", nil];
> NSEnumerator *enumerator = nil;
> NSString *colorString;
>
> // Draw concentric circles from the outside in
> for (float currentRadius = maxRadius;
> currentRadius > 0;
> currentRadius -= 20)
> {
> // Determine stroke color
> if (!(colorString = [enumerator nextObject])) {
> enumerator = [strokeColors objectEnumerator];
> colorString = [enumerator nextObject];
> }
> SEL selector = NSSelectorFromString(colorString);
> [[UIColor performSelector:selector] setStroke];
>
> // Do Drawing
> CGContextAddArc(context, center.x, center.y,
> currentRadius, 0.0, M_PI * 2.0, YES);
> CGContextStrokePath(context);
> }
>
> My question concerns the use the NSEnumerator here. The code works, but is it _right_? In particular, I'm slightly nervous about relying on the enumerator being nil first time through the loop, and on testing the return value of nextObject in the conditional -- perhaps though this is just an idiom I need to get used to?
So long as you're relying on documented behavior of NSEnumerator (which you seem to be), and so long as you can reason that your code's logic is correct, then your approach is fine.
However, in this case it makes your code hard to read (and verify) because it involves in recalling the documented behavior of NSEnumeration, plus reasoning that the code's logic is correct. What's wrong with the direct approach? The best enumerator is no enumerator (written in Mail):
> NSArray *strokeColors = [NSArray arrayWithObjects:
> [UIColor redColor], [UIColor orangeColor, [UIColor yellowColor], [UIColor greenColor],
> [UIColor blueColor], [UIColor cyanColor], [UIColor magentaColor], nil];
>
> NSUInteger colorIndex = 0;
> for (float currentRadius = maxRadius;
> currentRadius > 0;
> currentRadius -= 20)
> {
> [[strokeColors objectAtIndex: colorIndex++ % strokeColors.count] setStroke];
>
> // Do Drawing
> ...
> }
I don't need to look up any documentation to read that. :)
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please 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