Home > Articles > Home & Office Computing > Mac OS X

  • Print
  • + Share This
Like this article? We recommend

Categories, Avoiding Subclassing

Another way to avoid subclassing objects is by the use of Categories, which allow you to add methods to an existing class without subclassing that object. By adding a Category to a class, all instances of that class gain the Category within the scope of your application. You can also override an existing method by declaring it within a Category. To create a Category, it needs to be defined in a header file as follows:

#import "NSObject.h"

@interface NSObject (CategoryExample)

- (int)retainCount;

@end

After the header file is created, the implementation file would be as follows:

#import "CategoryExample.h"

@implementation NSObject (CategoryExample)

- (int)retainCount {
  return 0;
}

@end

In this simple example, I have caused retainCount to return zero for every single class in the entire application! This is because all classes extend from NSObject, and I have altered the behavior of the retainCount: method in NSObject itself. I have not extended NSObject, but have altered the behavior of NSObjet itself.

Categories are very useful in that they allow the developer to alter the behavior of an existing class without subclassing it and without having to repoint everything to the subclass. By simply adding a Category, additional behavior can be included with any class, and the entire application will gain the benefit of the additional methods.

Java does not have anything that resembles this functionality. In Java, there is no way to "inject" code into an existing class without subclassing that class or replacing it. Although this probably makes Java more secure, it certainly adds some very nice benefits to Objective-C development.

  • + Share This
  • 🔖 Save To Your Account