Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Category and Class Extension?

Tags:

objective-c

What is the difference between a Category and a Class Extension. I believe both are used to add custom methods in existing classes. Can someone throw light on this? Examplification with code will be really appreciated.

like image 853
Abhinav Avatar asked Aug 17 '10 06:08

Abhinav


People also ask

What is category in IOS?

You use categories to define additional methods of an existing class—even one whose source code is unavailable to you—without subclassing. You typically use a category to add methods to an existing class, such as one defined in the Cocoa frameworks.

What is category in Swift?

In Objective C they were called categories, but in Swift they are called extensions. The purpose of both of them are to give additional functionality to existing classes without having to create subclasses.

What is a category in Objective-C?

A category allows you to add methods to an existing class—even to one for which you do not have the source. Categories are a powerful feature that allows you to extend the functionality of existing classes without subclassing. Check the apple doc for the Category in Objective-C.

How do you extend a class in Objective-C?

The methods declared by a class extension are implemented in the implementation block for the original class, so you can't, for example, declare a class extension on a framework class, such as a Cocoa or Cocoa Touch class like NSString. Extensions are actually categories without the category name.


1 Answers

A category is a way to add methods to existing classes. They usually reside in files called "Class+CategoryName.h", like "NSView+CustomAdditions.h" (and .m, of course).

A class extension is a category, except for 2 main differences:

  1. The category has no name. It is declared like this:

    @interface SomeClass ()  
    - (void) anAdditionalMethod; 
    @end
  2. The implementation of the extension must be in the main @implementation block of the file.

It's quite common to see a class extension at the top of a .m file declaring more methods on the class, that are then implemented below in the main @implementation section of the class. This is a way to declare "pseudo-private" methods (pseudo-private in that they're not really private, just not externally exposed).

like image 101
Dave DeLong Avatar answered Sep 19 '22 17:09

Dave DeLong