category

You are browsing the category tag archive.

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] [...]