TweetFollow Us on Twitter

Jun 02 Cocoa

Volume Number: 18 (2002)
Issue Number: 06
Column Tag: Cocoa Development

by Dan Wood, Alameda CA

The Beauty of Categories

Use This Objective-C Feature to Make Your Cocoa Code Cleaner

Ask any experienced Cocoa programmer what they like the most about Objective-C and the answer will invariably be “categories.” Categories is one of the features of Objective-C, not found in Java or C++, that raises the body temperature of developers if you suggest they use another language.

What is It, and Why Use It?

A category is an extension of an existing class. But unlike inheritance, in which you create a new class that descends from another class, a category is like a remora, attaching itself to the belly of a shark and getting a free ride. By creating a category, you add new methods to an existing class, without needing to create a new one.

Writing in a language without categories, the programmer is often faced with the need to perform minor operations, acting upon an object for which source code is unavailable. These routines might end up as methods in the application class that needs to perform those operations, although that doesn’t promote reuseability, since the operations are tied in with the enclosing class. A better approach, one more commonly used, is to collect these operations into a utility class.

On an open-source web application framework that I worked on, called Janx (available at www.bearriver.com) there is a string utilities class, for example. This class has operations to parse strings representing dollars and cents, encode a string for HTML display, generate a hexadecimal representation, build an MD5 digest from a string, and so forth. Each of these methods takes a string to operate upon as one of its parameters.

This “utility class” approach isn’t particularly elegant either. Dissimilar operations tend to be grouped together into the same class. Each method must be passed in the object to operated upon as a parameter, which means that the functions that you write look and operate differently from methods that are part of the class, even if they perform similar operations.

Another approach to extending functionality is to create a subclass of an existing framework object, and add your new functionality into the subclass. For instance, you might subclass an existing “image” class to add operations. The problem is that you must now be sure to work only with instances of your new class; any objects that aren’t must be converted.

If you are programming in a language such as C++ or Java without categories, though, you just deal with these limitations; they may not seem like limitations at all.

When you write an application in Cocoa using Objective C, you have the ability to put such functions directly into an existing class by creating a category on that class. No, you don’t recompile the class with new methods in the file; in fact you usually don’t have the source code to the class you are adding to.

Utilities vs. Categories

Let’s take a look at how this might be done by implementing a utility function to strip quote marks off of a string. (We’ll implement them both in Objective-C just to keep the playing field level.) We implement it as a method in a string utility class in listing 1 and 2; we implement it as a category on NSString in listing 3 and 4.

Listing 1: StringUtilities.h

#import 
@interface StringUtilities
+ (NSString *) stripQuotes:(NSString *)inString;
@end

Listing 2: StringUtilities.m

#import "StringUtilities.h"
@implementation StringUtilities

+ (NSString *) stripQuotes:(NSString *)inString
{
   NSString *result = inString;      // Return inString if no stripping needed
   int len = [inString length];
   if (len >= 2
      && '"' == [inString characterAtIndex:0]
      && '"' == [inString characterAtIndex:len-1])
   {
      // Get the substring that doesn’t include first and last character
      result =
         [inString substringWithRange:NSMakeRange(1,len-2)];
   }
   return result;
}

Listing 3: NSString+misc.h

#import 
@interface NSString ( misc )
- (NSString *) stripQuotes;
@end

Listing 4: NSString+misc.m

#import "NSString+misc.h"
@implementation NSString ( misc )

- (NSString *) stripQuotes
{
   NSString *result = self;      // Return self if no stripping needed
   int len = [self length];
   if (len >= 2
      && '"' == [self characterAtIndex:0]
      && '"' == [self characterAtIndex:len-1])
   {
      // Get the substring that doesn’t include first and last character
      result = [self substringWithRange:NSMakeRange(1,len-2)];
   }
   return result;
}

The implementations of these category looks much like the utility class; the main difference is that the string to operate upon is not passed in as a parameter; it is accessed with the self keyword. Things start to look different when you compare code that uses the category instead of a utility class. Here are snippets that use each approach.

Snippet using a utility class

   NSString *stripped =
      [StringUtilities stripQuotes:theValue];
   [lineDict setObject:stripped
      forKey:[theKey uppercaseString]];

Snippet using a category

   NSString *stripped =
      [theValue stripQuotes];
   [lineDict setObject:stripped
      forKey:[theKey uppercaseString]];

The code using the category is quite a bit cleaner because we don’t have to be conscious of a separate utility class; it is just another operation on the string, just like the built-in uppercaseString method on the last line.

Writing Categories

A category must have an @interface and @implementation section, just as a class. After the name of the class being added to is an arbitrary name which describes what the category is for, in parentheses. The example above uses "misc" as its name.

Normally, a category on a class gets its own “.h” and “.m” file; a convention is to name the file based on the class name concatenated with “+” to the category name. For example, the file NSImage+bitmap.m would be expected to hold @implementation NSImage ( bitmap ). This is not strictly neccesary; however; you could make a quick category interface and implementation right in your class file that makes use of the category; this would only be practical if it was not needed outside of the associated class.

Methods are declared and implemented just as they would be for any standard Objective-C’s methods. Keep in mind, however that self is the class that you are implementing; feel free to send messages to self to operate on that object.

The one big limitation on categories is that you can only add functionality; you cannot add new data members to the class. There are no curly braces in the @interface section of a category. If you feel the need to add data members, you may want to consider subclassing instead.

Using Categories

The best thing about categories is that you can add whatever features to Cocoa you’d like to that you feel are “missing.” Frustrated that NSImage lacks the +[NSImage imageFromData:] method? Add it in yourself! You can write generic categories and use them on all your projects, and make use of them as if you were using functionality of the classes provided by Apple. Or, you can create categories on an object as needed, whenever it seems more intuitive to extend the functionality of a Cocoa class rather than write a function to act upon that object.

You can even use categories on your own code, to help factor your application’s classes into smaller, more manageable chunks. For instance, you might create separate categories to partition your document controller into preferences management, window management, and general functionality. Doing so makes your files smaller and makes your project more navigable. Cocoa itself makes heavy use of categories in this manner; it allows classes to be created in one library (such as Foundation Kit) and then extended in another (such as Application Kit).

One of the best places to use a category is to split up your class’s private methods from its public ones, to overcome a limitation in Objective-C. Unlike C++ and Java, there’s no way to specify the access of a method using keywords. So the solution is to create a new @interface for your category at the top of your class’s “.m” file, holding the methods you do not want to be exposed in the “.h” file. This category would have a name such as “private” to indicate its purpose. Below that, the @implementation section of your class can then hold the implementation of both the public methods (declared in the “.h” file) and the private methods (declared in your private category). Other classes will not be able to see your private methods.

Usually, you will find yourself adding categories to classes in the Foundation Kit, because this kit tends to hold containers and utilities. You can even add categories to NSObject so that any object can respond to your new functionality. When there is a technique that requires bridging into Carbon or Core Foundation to accomplish your task, you could wrap it into a category on a related class (or even find one online that somebody else has already written) , so that if such functionality were to make its way into a future version of Cocoa, your code wouldn’t have to change much.

Examples

Where you make use of categories is limited only by your imagination. It is useful to look at other people’s source code just to get a sense of what kinds of categories are possible. Many source code packages are available for downloading at softrak.stepwise.com.

Here are a few examples that I have used in my own code. To make use of these, you would need to create @interface and @implementation sections following the guidelines above.

Category for NSImage

A method to set an image size to be the size of its associated NSBitmapImageRepresentation so that the image displays at full size of 72 DPI. It finds the first bitmap it can, and sets the size of the bitmap and of the image to the pixel width and height.

- (NSImage *) normalizeSize
{
   NSBitmapImageRep   *theBitmap = nil;
   NSArray               *reps = [self representations];
   NSSize                  newSize;
   int                     i;
   
   for (i = 0 ; i < [reps count] ; i++ )
   {
      NSImageRep *theRep = [reps objectAtIndex:i]; 
      if ([theRep isKindOfClass:[NSBitmapImageRep class]])
      {
         theBitmap = (NSBitmapImageRep *)theRep;
         break;
      }
   }
   if (nil != theBitmap)      // Found a bitmap to resize
   {
      newSize.width = [theBitmap pixelsWide];
      newSize.height = [theBitmap pixelsHigh];
      [theBitmap setSize:newSize];      // resize bitmap
      [self setSize:newSize];            // resize image
   }
   return self;
}

Category for NSBundle, NSDictionary, NSString, etc.

A comparison method (passing in another object of the same) so that you can sort an array of those objects by some property, using -[NSMutableArray sortUsingSelector:]. For example, you could sort an array of dictionaries by the value of their “name” key by passing in the selector for the following method.

- (NSComparisonResult) compareSymbolName:
      (NSDictionary *) inDict
{
   NSString *myName = [self objectForKey:@"name"];
   NSString *otherName = [inDict objectForKey:@"name"];
   return [myName caseInsensitiveCompare:otherName];
}

Category for NSString

A method to return an attributed string as a blue underlined hyperlink, so that text fields can respond to link clicks as in a web browser. Text in an NSTextView with these attributes will send the message of textView: clickedOnLink: atIndex: to the view’s delegate.

- (NSAttributedString *)hyperlink
{
   NSDictionary *attributes=
      [NSDictionary dictionaryWithObjectsAndKeys:
         [NSNumber numberWithInt:NSSingleUnderlineStyle],
            NSUnderlineStyleAttributeName,
         self, NSLinkAttributeName,            // link to the string itself
         [NSFont systemFontOfSize:[NSFont smallSystemFontSize]],
            NSFontAttributeName,
         [NSColor blueColor], NSForegroundColorAttributeName,
         nil];
   NSAttributedString *result= 
      [[[NSAttributedString alloc]
         initWithString:self
         attributes:attributes] autorelease];
   return result;
}

Category for NSWorkspace

A method to return the path of the current user’s temporary directory. This makes use of the Carbon FindFolder() API, and then converts the C string into an NSString.

- (NSString *) temporaryDirectory
{
   char         s[1024];
   FSSpec      spec;
   FSRef      ref;
   short      vRefNum;
   long         dirID;
   
   if ( FindFolder(
      kOnAppropriateDisk, kChewableItemsFolderType, true,
         &vRefNum, &dirID ) == noErr )
   {
      FSMakeFSSpec( vRefNum, dirID, "", &spec );
      if ( FSpMakeFSRef(&spec, &ref) == noErr )
      {
         FSRefMakePath(&ref, s, sizeof(s));
         return [NSString stringWithCString:s];
      }
   }
   return nil;
}

Category for NSSet, NSArray, etc.

A method to build a string listing the strings in a collection, separated by commas. It enumerates through all objects in the structure, adding each string and then adding a comma. It then removes the extra comma (and space) at the end, after the list is traversed.

- (NSString *) show
{
   NSString               *result = @"";      // empty string if none in collection
   NSMutableString      *buffer = [NSMutableString string];
   NSEnumerator         *theEnum = [self objectEnumerator];
   NSString               *theIdentifier;

   while (nil != (theIdentifier = [theEnum nextObject]) )
   {
      [buffer appendString:theIdentifier];
      [buffer appendString:@", "];
   }
   // Delete final comma+space from the string
   if (![buffer isEqualToString:@""])
   {
      [buffer deleteCharactersInRange:NSMakeRange(
         [buffer length]-2, 2)];
      result = [NSString stringWithString:buffer];
   }
   return result;
}

Conclusion

Hopefully you have been convinced that categories are a useful construct for programming in Cocoa. If you’re not using Objective-C, you can certainly function without them. But if you are, then categories are a great way to make your code more readable, more reuseable, more maintainable, and simpler.


Dan Wood wrote Watson for Mac OS X, a Cocoa application that connects to a variety of Web services. You can reach him at dwood@karelia.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.