Ticker

6/recent/ticker-posts

Category in iOS || Objective-C

Category in iOS || Objective-C

The Category technique in iOS provides the way of adding extra behaviour to the your custom classes or existed Cocoa classes i.e, NSString, NSArray, Person, Education and so on. In the categories you can declare your custom methods and it’s implementation. 

  • Here in the categories you no need to subclass the any superclass.
  • When you writing categories for any class, you would not required it’s original implementation. 
  • There no no runtime difference with the scope of your program between the original methods of the class and the methods added by the category.
  • The methods in category become part of the class type and are inherited by all the class’s subclasses.

Limitations of adding categories

  • You can’t add instance variable to the class
  • If you override existing methods of the class, your application may behave unpredictably.

Simple example

Requirement - I wan to add a method the the NSDate class and which should return the formatted date string fro the date object.

So, let's get in to the coding part, fist create new project, Xcode/File/New/Project/Single View Application
 And name your project and the organisation details. 
After creating your new project let's category file, to create category file go to File/New/File/iOS/Objective-C File

Name your category and select the file type as Category and also specify the class you want to add the category
After clicking on next it will generates to file like NSDate+Formatted.h and NSDate+Formatted.m, So let's add the following code to your .h file and also to the .m file


Post a Comment

0 Comments