Difference between Category and Class Extension?
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:
The category has no name. It is declared like this:
@interface SomeClass ()
@end- (void) anAdditionalMethod;
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).
- Category
=> In Objective C, when you want to add some more functionality to a class without inheritance, you simply use category for it.
=> it comes with its own .h and .m file
=> Category
uses to add new method not properties.
- Class Extension
-> In Objective C, when you want to make behaviour of some property private you use class extension.
-> it comes with **.h** file only.
-> mainly for properties.
Note: when we add a new file and select a option of objective c category shows category and "category on" not "subclass of" so it shows like
@interface className (categoryName)
@end
-You will get two file .h and .m with file name as (className+categoryName.h and className+categoryName.m)
and in extension case you will get
@interface className()
@end
-You will get only one file with name as className_extensionName.h
- In category you don't own the class but in extension you are.
Category is a way to add methods to a class whether or not source code is available, meaning you can add category to foundation classes like
NSString
and also to your own custom classes.Extension can only be added to the classes whose source code is available because compiler compiles the source code and extension at the same time.
We can add extra instance variables and properties in class extension but not in category.
Any variable and method inside the extension is not even accessible to inherited classes.
Category and extension both are basically made to handle large code base, but category is a way to extend class API in multiple source files while extension is a way to add required methods outside the main interface file.
Use category when you have to break your same class code into different source files according to different functionalities, and extension when you just need to add some required methods to existing class outside the main interface file. Also, when you need to modify a publicly declared instance variable in a class, for example, readonly to readwrite, you can re-declare it in extension.