How to Add Methods to Existing Class in iOS App Development - dummies

How to Add Methods to Existing Class in iOS App Development

By Rajiv Ramnath

In iOS app development, Objective-C allows you to add your own methods to existing classes, even those classes that you have not written. Adding additional methods to a class is useful in a situation where the new behavior is used only in certain situations.

As an example, you might find that a particular application (say, a palindrome checker) needs to reverse pretty much any string it is dealing with! It might make your program overly complicated to create your own subclass of NSString with the additional reverse method. Rather, you might find it much more convenient to add the new behavior to the original class.

Note you can’t modify the original interface or implementation NSString because it is a framework class and you don’t have the source code. However, you can extend the NSString class (or any other class) by defining a new category. In the file PostfixAll.m you will see that the NSString class has been extended with a method named reverse as follows:

@interface NSString (ReversibleString)
 - (NSString *)reverse;

As you can see, defining a category is very similar to defining an interface for a class. In fact, providing an implementation for the methods of a category is also very similar to providing the implementation for a class in that the methods are enclosed in an @implementation block. You can see the implementation block for the category below (in the file PostfixAll.m):

@implementation NSString (ReversibleString)
 - (NSString *)reverse {
  NSMutableString *reversedString = [[NSMutableString alloc] init];
  int stringLength = self.length;
  for (int i=stringLength-1; i >=0; i--){
   NSString *oneCharString =
    [self substringWithRange:NSMakeRange(i, 1)];
   [reversedString appendString:oneCharString];
  return reversedString;

Finally, the use of a method defined in a category is no different from the use of any other method, as can be seen from the following code snippet taken from the main function of PostfixAll.m:

 NSLog(@"Printing reversed string>%@<", [aStringObject reverse]);