Hi guys, hope you find the articles i have posted before, interesting and useful. I always welcome your feedback to make the future articles more interesting.Today lets see what is subclassing, categories and extensions in Objective C, and where, when and how to use these concepts.
1) Subclass in Objective C
2) Categories in Objective C
An Objective C category provide the ability to add functionality to an object without subclassing or changing the actual object. Categories let you expand the API of existing classes without changing their type such as NSString or your own custom objects & allows you add your own methods to an existing class. Categories are also called as "informal protocols".
Suppose take an example, since Foundation Framework classes such as NSString, NSArray, NSDate etc… doesn’t have any access to modify, you can add your own methods in to these classes by the help of a category.
Consider NSString Class and if suppose we want to add a reverse string method to NSString class, so that in our application at any point of time any NSString object can call this category method and get a reversed string as a result. We can do this as below,
Usually naming convention for category file is like OriginalClassName+CategoryName
Note: in a category you can’t add an instance variable, since methods within a category are added to a class at runtime.
3) Extensions in Objective C
A class extension is used to declare additional interface -- methods and properties -- whose implementation contract will be met within the class's primary
Extensions are similar to categories but the need of extension is different.
- Class extensions are often used to extend the public interface with additional private methods or properties for use within the implementation of the class.
- Extensions can only be added to a class for which you have the source code at compile time (the class is compiled at the same time as the class extension).
- Extensions will be local to a class file.
The syntax to declare class extension looks like,
since no name is given in the parentheses, class extensions are often referred to as anonymous categories. Usually people will use extensions to hide private information of a class without exposing them to access from any other class.
Note: Extensions can add instance variables.