Twitter Stream

Flickr Photos

Objective-C Rocks Your Socks

Saturday, January 20th, 2007

People who don’t know a thing about Objective-C are always asking me why I’d want to learn a special language “just for Mac programming” or why I like it more than most other programming languages in general. I think this is a great code snippet that made me stop and say you could NOT do this so elegantly in C++ or many other languages.

NSArray *participants = [archive valueForKey:@"participants"];
NSEnumerator *en = [participants objectEnumerator];
User *user = nil;

while (user = [en nextObject]) {                    
    // do stuff with the user
}

So what’s fascinating about this simple block of code? Let me explain. Lets say archive is a regular NSDictionary object, and participants is an OPTIONAL key/value in this dictionary which could contain an array of Users. How does that affect the rest of our code? Well that means the NSArray participants will be nil. So what happens when you call objectEnumerator on a nil object? An error? Nope! calling a message (any message) on an nil object returns nil. So that means en, our enumerator, becomes nil. Now when we get to our while loop calling nextObject on en will also return nil. Thus the loop terminates gracefully without any error checking code, an no sig-faults from calling our “nil” objects. I’ve just written code that not only performs it’s task but gracefully degrades even under optional conditions.