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

Minecraft 1.20.2 - Popular sandbox build...
Minecraft allows players to build constructions out of textured cubes in a 3D procedurally generated world. Other activities in the game include exploration, gathering resources, crafting, and combat... Read more
HoudahSpot 6.4.1 - Advanced file-search...
HoudahSpot is a versatile desktop search tool. Use HoudahSpot to locate hard-to-find files and keep frequently used files within reach. HoudahSpot is a productivity tool. It is the hub where all the... Read more
coconutBattery 3.9.14 - Displays info ab...
With coconutBattery you're always aware of your current battery health. It shows you live information about your battery such as how often it was charged and how is the current maximum capacity in... Read more
Keynote 13.2 - Apple's presentation...
Easily create gorgeous presentations with the all-new Keynote, featuring powerful yet easy-to-use tools and dazzling effects that will make you a very hard act to follow. The Theme Chooser lets you... Read more
Apple Pages 13.2 - Apple's word pro...
Apple Pages is a powerful word processor that gives you everything you need to create documents that look beautiful. And read beautifully. It lets you work seamlessly between Mac and iOS devices, and... Read more
Numbers 13.2 - Apple's spreadsheet...
With Apple Numbers, sophisticated spreadsheets are just the start. The whole sheet is your canvas. Just add dramatic interactive charts, tables, and images that paint a revealing picture of your data... Read more
Ableton Live 11.3.11 - Record music usin...
Ableton Live lets you create and record music on your Mac. Use digital instruments, pre-recorded sounds, and sampled loops to arrange, produce, and perform your music like never before. Ableton Live... Read more
Affinity Photo 2.2.0 - Digital editing f...
Affinity Photo - redefines the boundaries for professional photo editing software for the Mac. With a meticulous focus on workflow it offers sophisticated tools for enhancing, editing and retouching... Read more
SpamSieve 3.0 - Robust spam filter for m...
SpamSieve is a robust spam filter for major email clients that uses powerful Bayesian spam filtering. SpamSieve understands what your spam looks like in order to block it all, but also learns what... Read more
WhatsApp 2.2338.12 - Desktop client for...
WhatsApp is the desktop client for WhatsApp Messenger, a cross-platform mobile messaging app which allows you to exchange messages without having to pay for SMS. WhatsApp Messenger is available for... Read more

Latest Forum Discussions

See All

‘Resident Evil 4’ Remake Pre-Orders Are...
Over the weekend, Capcom revealed the Japanese price points for both upcoming iOS and iPadOS ports of Resident Evil Village and Resident Evil 4 Remake , in addition to confirming the release date for Resident Evil Village. Since then, pre-orders... | Read more »
Square Enix commemorates one of its grea...
One of the most criminally underused properties in the Square Enix roster is undoubtedly Parasite Eve, a fantastic fusion of Resident Evil and Final Fantasy that deserved far more than two PlayStation One Games and a PSP follow-up. Now, however,... | Read more »
Resident Evil Village for iPhone 15 Pro...
During its TGS 2023 stream, Capcom showcased the Following upcoming ports revealed during the Apple iPhone 15 event. Capcom also announced pricing for the mobile (and macOS in the case of the former) ports of Resident Evil 4 Remake and Resident Evil... | Read more »
The iPhone 15 Episode – The TouchArcade...
After a 3 week hiatus The TouchArcade Show returns with another action-packed episode! Well, maybe not so much “action-packed" as it is “packed with talk about the iPhone 15 Pro". Eli, being in a time zone 3 hours ahead of me, as well as being smart... | Read more »
TouchArcade Game of the Week: ‘DERE Veng...
Developer Appsir Games have been putting out genre-defying titles on mobile (and other platforms) for a number of years now, and this week marks the release of their magnum opus DERE Vengeance which has been many years in the making. In fact, if the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for September 22nd, 2023. I’ve had a good night’s sleep, and though my body aches down to the last bit of sinew and meat, I’m at least thinking straight again. We’ve got a lot to look at... | Read more »
TGS 2023: Level-5 Celebrates 25 Years Wi...
Back when I first started covering the Tokyo Game Show for TouchArcade, prolific RPG producer Level-5 could always be counted on for a fairly big booth with a blend of mobile and console games on offer. At recent shows, the company’s presence has... | Read more »
TGS 2023: ‘Final Fantasy’ & ‘Dragon...
Square Enix usually has one of the bigger, more attention-grabbing booths at the Tokyo Game Show, and this year was no different in that sense. The line-ups to play pretty much anything there were among the lengthiest of the show, and there were... | Read more »
Valve Says To Not Expect a Faster Steam...
With the big 20% off discount for the Steam Deck available to celebrate Steam’s 20th anniversary, Valve had a good presence at TGS 2023 with interviews and more. | Read more »
‘Honkai Impact 3rd Part 2’ Revealed at T...
At TGS 2023, HoYoverse had a big presence with new trailers for the usual suspects, but I didn’t expect a big announcement for Honkai Impact 3rd (Free). | Read more »

Price Scanner via MacPrices.net

New low price: 13″ M2 MacBook Pro for $1049,...
Amazon has the Space Gray 13″ MacBook Pro with an Apple M2 CPU and 256GB of storage in stock and on sale today for $250 off MSRP. Their price is the lowest we’ve seen for this configuration from any... Read more
Apple AirPods 2 with USB-C now in stock and o...
Amazon has Apple’s 2023 AirPods Pro with USB-C now in stock and on sale for $199.99 including free shipping. Their price is $50 off MSRP, and it’s currently the lowest price available for new AirPods... Read more
New low prices: Apple’s 15″ M2 MacBook Airs w...
Amazon has 15″ MacBook Airs with M2 CPUs and 512GB of storage in stock and on sale for $1249 shipped. That’s $250 off Apple’s MSRP, and it’s the lowest price available for these M2-powered MacBook... Read more
New low price: Clearance 16″ Apple MacBook Pr...
B&H Photo has clearance 16″ M1 Max MacBook Pros, 10-core CPU/32-core GPU/1TB SSD/Space Gray or Silver, in stock today for $2399 including free 1-2 day delivery to most US addresses. Their price... Read more
Switch to Red Pocket Mobile and get a new iPh...
Red Pocket Mobile has new Apple iPhone 15 and 15 Pro models on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide service using all the major... Read more
Apple continues to offer a $350 discount on 2...
Apple has Studio Display models available in their Certified Refurbished store for up to $350 off MSRP. Each display comes with Apple’s one-year warranty, with new glass and a case, and ships free.... Read more
Apple’s 16-inch MacBook Pros with M2 Pro CPUs...
Amazon is offering a $250 discount on new Apple 16-inch M2 Pro MacBook Pros for a limited time. Their prices are currently the lowest available for these models from any Apple retailer: – 16″ MacBook... Read more
Closeout Sale: Apple Watch Ultra with Green A...
Adorama haș the Apple Watch Ultra with a Green Alpine Loop on clearance sale for $699 including free shipping. Their price is $100 off original MSRP, and it’s the lowest price we’ve seen for an Apple... Read more
Use this promo code at Verizon to take $150 o...
Verizon is offering a $150 discount on cellular-capable Apple Watch Series 9 and Ultra 2 models for a limited time. Use code WATCH150 at checkout to take advantage of this offer. The fine print: “Up... Read more
New low price: Apple’s 10th generation iPads...
B&H Photo has the 10th generation 64GB WiFi iPad (Blue and Silver colors) in stock and on sale for $379 for a limited time. B&H’s price is $70 off Apple’s MSRP, and it’s the lowest price... Read more

Jobs Board

Housekeeper, *Apple* Valley Villa - Cassia...
Apple Valley Villa, part of a 4-star senior living community, is hiring entry-level Full-Time Housekeepers to join our team! We will train you for this position and Read more
Housekeeper, *Apple* Valley Village - Cassi...
Apple Valley Village Health Care Center, a 4-star rated senior care campus, is hiring a Part-Time Housekeeper to join our team! We will train you for this position! Read more
Optometrist- *Apple* Valley, CA- Target Opt...
Optometrist- Apple Valley, CA- Target Optical Date: Sep 23, 2023 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 796045 At Target Read more
Senior *Apple* iOS CNO Developer (Onsite) -...
…Offense and Defense Experts (CODEX) is in need of smart, motivated and self-driven Apple iOS CNO Developers to join our team to solve real-time cyber challenges. Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.