Enumerating collections

This post is describes techniques to enumerate your objects in a data collection, in this case an NSArray.

Using a typical for loop.

for (int i=0; i<=[myArray count]; i++){
id myObject = [myArray objectAtIndex:i];
// do something with the object
}

Using the NSEnumerator.

NSEnumerator * enum = [myArray objectEnumerator];
while (id myObject = [enum nextObject]){
// do something with the object
}

A much more concrete example can be found here.

Using Fast enumeration.

for (id myObject in myArray) {
// do something with the object
}

Using makeObjectsPerformSelector which is not considered as a different method but it could be very handy in some cases:

[newArray makeObjectsPerformSelector:@selector(doSomething)];

Which is equivalent to:

for (id myObject in myArray) {
[myObject performSelector:@selector(doSomething)];
}

Notes to take under consideration:

  • The id could be replaced with a type.
  • Enumerating mutable collection can raise exceptions
  • Fast enumeration is faster than the others, According to Apple “The enumeration is considerably more efficient than, for example, using NSEnumerator directly.” so is worth checking it out.
  • You can use this on your own collection classes by implementing the NSFastEnumeration protocol.
  • For makeObjectsPerformSelector read here for some insights

More information here

Loop in your Home directory

I wanted to implement a method that will go through all my files in my home directory. I couldn’t believe how easy that was. I have done it in C before and it was really really hard! Thank God, cocoa does it with a few lines:

1
2
3
4
5
6
7
8
NSString *path = [NSString stringWithFormat:@”%@/”,NSHomeDirectory()]; 
NSFileManager *manager = [NSFileManager defaultManager];
NSDirectoryEnumerator *dirEnum = [manager enumeratorAtPath:path];
NSString *file;
 
while (file = [dirEnum nextObject]){
	NSLog(@”%@”,file );
}