An Introduction to Categories (Part 1 of 2)

November 4th, 2010 Posted by: James Van Metre - posted under:Featured » Tutorials

Overview

Have you ever wished that you could add one, or a couple, additional functions to an Objective-C core class?
Well Apple has thought of this, and they provide a way without extended the class! The way to do this is called a category. A category is a way to enhance an existing class, by adding additional functions to it. The difference between this and extending a class is that when you extend a class, you can add additional functions, as well as variables. In a category, you can only add additional functions. The benefit of a category though is that you don’t have to use the extended class to get the benefits of the added additional functions. All you have to do is include the header file of the category, and the additional functions of that class are available to you.

A Simple NSDate example

Say we have an NSDate object, and we know that we want it to always be formatted a certain way. You can create an NSDate category, with an additional function called getFormattedString, that will always return an NSString * with the current date formatted a certain way.

How it’s Made

We will start with a simple view based project, that includes two UITextField’s, that we will use to output our dates. I will leave it up to you to create this on your own, or download the entire project from .

Categories typically have the convention of ClassName+OurText.m, so we create a new file of subclass NSObject, called NSDate+FormatString.m, make sure to check “Also create NSDate+FormatString.h”. After creating those files, we need to make some minor changes to them to actually have them be treated as categories. In the header file, change

@interface NSDate_FormatString : NSObject {
 
}
@end

to

@interface NSDate (FormatString)
 
@end

making sure to remove the brackets, in the header file. The reason for this is that a category can not add variables, only functions.

In the implementation file, change

@implementation NSDate_FormatString

to

@implementation NSDate (FormatString)

We have now created a category! This of course doesn’t do anything yet, so lets add some meat to it.

// In NSDate+FormatString.h, after @interface add
- (NSString *)getFormattedString;
 
// And in NSDate+FormatString.m, after @implementation add
- (NSString *)getFormattedString {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"MM/dd/yyyy h:mm a"];
        NSString *returnDate = [formatter stringFromDate:self];
        [formatter release];
        return returnDate;
}

Now to use this category, all we have to do is add

#import "NSDate+FormatString.h"

to any file where we have an NSDate, and we will be able to call

NSDate *today = [NSDate date]; //get the current date
NSLog(@"The current date is: %@", [today getFormattedString]);

This will print out today’s date all nicely formatted for you!

We use this to output a formatted date to our textfield

- (IBAction)dateButtonClicked:(id)sender {
        NSDate *today = [NSDate date];
        originalDateField.text = [today description];
        formattedDateField.text = [today getFormattedString];
}

Of course this is just a very basic example of using a Category. On my next installment I will cover using Categories to add functions to generated Core Data Model classes, and more fun things!

Get this project on !

  • http://www.swanify.com Matthew Lanham

    Nice tutorial, easily to follow…

  • http://icode.dreamvision-soft.com/blog/?p=92 An Introduction to Categories (Part 1 of 2) | iCode

    [...] Original post on iCodeBlog [...]

  • http://twitter.com/jakerocheleau Jake Rocheleau

    Awesome introduction to Objective-C for iOS development. This is a neat framework, will come in handy when messing around in XCode

  • http://www.scripting.chaindb.com Guyven69

    nice! now i know, i’m just started using objective-c programming

  • http://fruitandrobots.wordpress.com/ Jason Nezumi

    Another interesting use of categories is to provide private methods. If you create your header file, then place a category definition above the @implementation directive in your implementation file, you can write your category methods inside the standard definition right along with the rest of the class, but they won’t have the visibility of the interface methods.

    Interestingly, it turns out there are a few quirks with categories–if you need to inspect an object at runtime to see if it responds to a given selector, there’s some kind of weirdness with whether category methods will show as supported or not. This is a very little-used feature, though, so I imagine few people will have to worry about it.

  • drebman

    test

  • Anonymous

    It seems as though Birkin Handbags Kanye West is has been mighty controversial some people believe he is , some men and women think he tweets too much, and still other people have yet to get over that entire Taylor Swift thing. In case you’re not familiar with the , Birkin Handbags small monsters is the name that she uses to refer to her fans, so her Birkin message was a shout-out to those that would be attending her Japanese shows. Birkin Handbags Utilizing accessories along with the paparazzi to communicate clever, or not so much?The deal with looks a bit worse for the wear womens shoes,Hermes Birkin Handbags but I am digging the distressing on the rest of the bag and how aged the leather is. When you have any information on the name of this model or the year it could have been made , let us know inside the contents Kanye, naturally, was short on details.I have decided that Lady Gaga Hermes Birkin Handbags performs makeovers on her Hermes Birkins just for us. She wants the handbag lovers of the world to get a rise out of what she is performing to her bag. UPDATE: , it looks as though Gaga Hermes Birkin Handbags has now had her Japanese fans sign the back of the same Birkin, according the the pictures that she posted on Twitter these days.Hermes Bags Short films as seasonal promos have turn out to be the thing to do in fashion over the past few seasons (we probably have Karl Lagerfeld to thank for that), and Hermes is the latest brand to jump on the bandwagon (or, by the looks of this video, jump on the horse-drawn cart) with Hermes Bags for Fall/Winter 2010. The video is under two minutes and focuses largely on handbags and accessories,Hermes Bags which appears like the ideal method to begin the weekend to us.If you’re a fan of the Hermes Birkin (or simply not a fan of Lady Gaga), gird your loins for this 1.Looking through the pictures of an Hermes runway show can be nearly anticlimactic Hermes Birkin we know that Jean Paul Gaultier is going to do something brilliant and that Hermes only uses the absolute most effective in luxury materials and finishes. They have set such a high bar for themselves that even though the team behind the brand practically constantly turns out brilliant work, Hermes Birkin I come across that the attitude tends to be, Hermes Birkin Of course it really is good. It is Hermes.Their perfection can feel . As for the bags, you seriously can not go wrong with an enormous black crocodile Birkin. Or black croc anything it was abundant in this show.