What is Categories in Objective-C.?


Q.32 What is Categories in Objective-C.? Ans:-

  • By using categories it is possible to add new method to existing class without using subclass.(Inheritance)
  • TO implement the categories we dosen’t require existing class related .h and .m file.
  • Categories can be refer like class extension also.
  • A category can be declare for any classes even if we dn’t having orignal implementation source code such as for standers Cocoa or Cocoa TOuch classes.
  • Objective-C Categories provide the ability to add functionality to an object without subclassing or changing the actual object.
  • Genarally categories required to use to add the methods to existing classes like, NSString or our custom object also.
  • Subclassing is one way to add the functionality to on object but avoiding unneccessory. subclassing by using a category will help to reduce the amount of code and keep your project more organized.
  • In following case always recommended to go for categories.

  1. Extending and existing cocoa class.
  2. Class Extension
  3. Private method on a class.
    Syntax to create categories.
  • @inteface Class_Name(Category)
    Data members;
    Member Functions;
    @end
  • Always category related interface section should be exist within the headers file only.
  • @implementaion Class_Name(Category)
    Method Code
    @end
  • Note*:
    When we are working with the categories it will allow to add the method to existing class only i.e it is not possible to add any instance variable to the categories.
  • In implementation if we required instance variable to any existing class then, it must be required to go for class extension.

Kalavati Technologies Pvt Ltd