Category and How to use it ?

Why use category?

Categories provide the ability to add functionality to an object without subclassing or changing the actual object.Suppose we want to remove numbers from string whenever we encountered in our project.So instead of  declare and defining it again and again, we make a category of it to our NSString class.

For this first we have to  cretae a category class by adding a file to our peoject.You can do this by

Click File > New > File and choose a Cocoa Touch Objective-C category from the window. Click “Next.” Name your category “RemoveNums” and select NSString from the “Category on” drop down menu (you may need to type this in manually). Click “Next” followed by “Create.”

in .h

@interface NSString (RemoveNums)

-(NSString *)removeNumbersFromString:(NSString *)string;


then define it in .m

– (NSString *)removeNumbersFromString:(NSString *)string


NSString *trimmedString = nil;

NSCharacterSet *numbersSet = [NSCharacterSet characterSetWithCharactersInString:@”0123456789″];

trimmedString = [string stringByTrimmingCharactersInSet:numbersSet];

return trimmedString;


Here, we are done with our category creation.Now time to use it

In your viewController, import it

#import “NSString+RemoveNums.h”

To test it, write down in viewDidLoad

NSString *stringWithNums = @”ABC 123″;

NSLog(@”stringWithNums         –> %@”,stringWithNums);

stringWithNums = [stringWithNums removeNumbersFromString:stringWithNums];

NSLog(@”trimmed stringWithNums –> %@”,stringWithNums);

That’s all. Hope you enjoyed it..

Note:-Taken from


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s