What is the difference between inheritance and Categories in Objective-C

Sometimes, inheritance just seems like more trouble than it is worth. It is correctly used when you want to add something to an existing class that is a change in the behaviour of that class.

With a Category, you just want the existing object to do a little more. As already given, if you just want to have a string class that handles compression, you don’t need to subclass the string class, you just create a category that handles the compression. That way, you don’t need to change the type of the string classes that you already use.

The clue is in the restriction that categories only add methods, you can’t add variables to a class using categories. If the class needs more properties, then it has to be subclassed.(edit: you can use associative storage, I believe).

Categories are a nice way to add functionality while at the same time conforming to an object oriented principle to prefer composition over inheritance.

Edit January 2012

Things have changed now. With the current LLVM compiler, and the modern, 64-bit runtime, you can add iVars and properties to class extensions (not categories). This lets you keep private iVars out of the public interface. But, if you declare properties for the iVars, they can still be accessed / changed via KVC, because there is still no such thing as a private method in Objective-C.

Leave a Comment