Fast Enumeration

I was looking at some client code and saw essentially this:

NSArray *items = [NSArray arrayWithObjects:@"one", @"two", @"three", @"four", nil];

MyClass *myClass = [[MyClass alloc] init];

for (int i=0; i<4; i++) {

    myClass.thing = @”test”;

    myClass.widget = [items objectAtIndex:i];

    // …

}

There are several issues, among them:

  • In the for loop the termination value is hard coded, if the number of items in the NSArray constant are changed the code will break. This could have be averted by using items.count
  • The indexing into the NSArray is not close to the declaration of the index (“i”) and is easily missed.
  • It is not clear if the index (“i”) is used elsewhere in the loop.

Fast enumeration could be used eliminating the above three issues.

Fast enumeration example:

NSArray *items = [NSArray arrayWithObjects:@"one", @"two", @"three", @"four", nil];

MyClass *myClass = [[MyClass alloc] init];

for (NSString *item in items) {

    myClass.widget = item;

    myClass.thing = @”test”;

    // …

}

No lines of code are eliminated, that is not the point, what is important is that the code is future-proofed and is more clear.

About zaph

Long term Mac/iOS & Cocoa developer.
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply