Ad space (banner)
🍎Objective-C Lessons
Lesson 16 / 68

Extending a class with a category

This lesson covers extending an existing class with an Objective-C category, with the aim of reusing code across classes that share a capability.

A category adds new methods to an existing class — including classes from the standard library. It is a way of extending that is distinct from inheritance and particular to Objective-C.

The sample code adds a new shout method to the existing NSString class by writing @interface NSString (Shout). Note how [@"hello" shout] calls it as though it had been there all along.

A common early stumble is the difference between a category and inheritance. Inheritance creates a new class; a category adds methods directly to the existing one — a more direct kind of extension.

In professional work, categories are a characteristic Objective-C technique for adding convenient methods to standard classes.

πŸ“– Reference code
✍️ Your code
Type your code, then press "Run"

πŸ§ͺ This site can't compile or run Objective-C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser β€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)