Warning: join(): Invalid arguments passed in /home/troyb/troybrant.net/blog/wp-content/themes/hybrid-hacked/hybrid-hacked/library/functions/breadcrumbs.php on line 79

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.

17 Responses to “Adding firstObject to NSArray”

  1. 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.

  2. @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”.

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

  4. Hi, do not forget to implement removeFirstObject too … because there is a removeLastObject too.

  5. Oh my goodness! Awesome article dude! Many thanks, However I am encountering difficulties with your RSS.
    I don’t know the reason why I cannot subscribe to it. Is there anyone else having the same RSS problems? Anyone that knows the answer will you kindly respond? Thanx!!

  6. There are some attention-grabbing points on this article however I don’t know if I see all of them close to heart. There is some validity but I will take hold an opinion til I look into it further. Great site, thanks and we want more! Added to FeedBurner as well.

  7. I feel extremely lucky to have seen your blog and look forward to more pleasurable visits here.

  8. I was very pleased to find this website. I wanted to say thanks for this informative post.

  9. Certain facts in this article are unquestionably the best I’ve ever read.

  10. A great share, I have simply given this along a colleague who was doing a bit similar research on this. He actually purchased lunch for me because I discovered this for him, thanks!

  11. I needed to send a small sentence in order to thank you very much on your pleasant concepts you’ve contributed in this article.

  12. Let heer shine, his tongie to conceive, nor our wway straight.
    If they are and you are completely insane and dominate the plot.
    The Placing is las vegas shows conditional upon,
    Be it soo nicely. If we shadows have offended, las vegas shows Think but this,
    which he hoped TS Eliot miught be the nice guy.

  13. Your feet swell during running, as much as a full shoe size.
    Whether it’s in your neck, back, feet, or any part of the body, our
    bodies should not hurt, and we should not have to compensate for pain. My mother and
    my grandmother are very calm people who seem to
    handle stress very well.

  14. Applying ice to swollen areas and taking anti-inflammatory medications may relieve some
    of the pain. If the injury is not severe, the recovery should be fast.
    If you don’t know the cause of a pain, tap on the image of that pain and you’ll probably get a measure of relief.

  15. Your feet swell during running, as much as a full shoe
    size. At this time, their body temperature drops and their heart rate can decrease from 200
    beats per minute (bpm) to 10 bpm. My mother and my grandmother are very calm people who seem to handle stress very well.

  16. The main problem lies in where the fungus is living:
    under the nail. If the injury is not severe, the recovery should be fast.
    Sometimes, more than one viral culture test may be
    requested by the physician to diagnose herpes infection as the lesion may have very little active virus and the test may produce a ‘false negative.

  17. Princeton Autonomous Vehicle Engineering (PAVE) is interested in establishing a facility for autonomous vehicle research at Fort Monmouth, according to minutes of an Oct. 3 meeting of the Fort Monmouth Economic Revitalization Agency. PAVE, a research group at Princeton University dedicated to advancing and promoting the field of robotics, hosted a meeting on fort grounds about the proposal.

Leave a Reply