Pages

Thursday, March 11, 2010

Loop For

Today I found a wonderful blog: Able Pear Software. Here is first two posts I read there:
1. Objective-C Tuesdays: The for loop
2. Objective-C Tuesdays: for loop variations
Sure, the subject is trivial. But the explanation is perfect. Simple and clear.
Next tutorial Objective-C Tuesdays: The for...in loop shows new things. For example, the following program uses an enumerator to print out the elements of NSSet:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSSet *items = [NSSet setWithObjects:@"foo", @"bar", nil];
NSEnumerator *enumerator = [items objectEnumerator];
NSString *item = nil;
while (item = [enumerator nextObject]) {
NSLog(item);
}

[pool drain];
return 0;
}
The program output looks so:
[Session started at 2010-03-11 22:26:59 +0200.]
2010-03-11 22:27:00.008 Enumerator[4905:903] foo
2010-03-11 22:27:00.014 Enumerator[4905:903] bar

The Debugger has exited with status 0.
For NSArray it is obviously to use for-loop. NSSet does not have a well defined order, so NSEnumerator used to be the only option. Now, the same task can be solved with for..in-loop:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSSet *items = [NSSet setWithObjects:@"foo", @"bar", nil];
NSString *item = nil;
for (item in items) {
NSLog(@"item = %@", item);
}

[pool drain];
return 0;
}
Same with NSArray:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSArray *collection = [NSArray
arrayWithObjects:@"foo", @"a", @"bar", @"baz", nil];
for (NSUInteger i = 0; i < collection.count; i++) {
NSString *item = [collection objectAtIndex:i];
NSLog(@"item '%@'", item);
}
[pool drain];
return 0;
}
And with the for..in loop:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSArray *collection = [NSArray
arrayWithObjects:@"foo", @"a", @"bar", @"baz", nil];
for (NSString *item in collection) {
NSLog(@"item '%@'", item);
}
[pool drain];
return 0;
}

No comments:

Post a Comment