Adding firstObject to NSArray

NSArray has a lastObject method. So, of course there is a matching firstObject method, right?

Nope.

If that oversight annoys you to no end, drop this simple category in your code, and say goodbye to all those ugly [array objectAtIndex:0]’s.

// NSArray+FirstObject.h

#import <Foundation/Foundation.h>

@interface NSArray (FirstObject)

- (id)firstObject;

@end

// NSArray+FirstObject.m

#import "NSArray+FirstObject.h"

@implementation NSArray (FirstObject)

- (id)firstObject
{
    if ([self count] > 0)
    {
        return [self objectAtIndex:0];
    }
    return nil;
}

@end

When you need the first element of an array (a common enough task) just use firstObject:

#import "NSArray+FirstObject.h"

NSArray *shows = [NSArray arrayWithObjects:@"Chuck", @"Caprica", @"LOST", nil];

NSString *firstShow = [shows objectAtIndex:0];
NSString *firstShow = [shows firstObject];

Ah, much better.

3 Responses to “Adding firstObject to NSArray”

  1. Nice. Goes well with my addition of simple sorting (http://owainrhunt.com/post/374809142). Sometimes the verbosity of ObjC is necessary, sometimes not.

  2. There’s a reason there’s no “firstObject”: It’s not needed.
    Object #0 *ALWAYS* is the 1st object.

    Doing all that extract/unneeded work… to create your own firstObject is like saying:
    The first book on that shelf is the first book.

    Your code is an excellent example of “categories”… but used in a pointless way.

    “Category” is a VERY powerful thing. Use it as such.

  3. @Jill:

    Well, at first glance your statement appears to be valid.
    Yet upon further inspection you should notice a subtle difference between

    [array objectAtIndex:0];
    [array firstObject];

    Try to run those two on an empty array.
    Result: The former method will throw an exception whereas the latter (category) method does not, returning nil instead. Just like Apple’s “[array lastObject]” uses to do it.

    Summing up: [array objectAtIndex:0] != [array firstObject] and by that in no way “pointless”.

Leave a Reply