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.
#import <Foundation/Foundation.h>
@interface NSArray (FirstObject)
- (id)firstObject;
@end
#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:
NSArray *shows = [NSArray arrayWithObjects:@"Chuck", @"Caprica", @"LOST", nil];
NSString *firstShow = [shows objectAtIndex:0];
NSString *firstShow = [shows firstObject];
Ah, much better.
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.
@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”.
Kent Beck in his implementation patterns book talks about symmetry, matching levels of abstractions throughout your code, so if there’s a lastObject, it makes sense there should be should be a firstObject too. There have been edge cases when I’ve used [array objectAtIndex: 0] in certain situations during coding and thought it was ‘ugly’ and didn’t fit in with the level of abstraction in my code at the time; perhaps it’s a style thing, a level-of-abstraction thing, who knows – maybe there should be methods [array head] and [array tail]