Objective-C Category

Many times, you want to extend an existing class just by adding the behaviour, which is useful in some situations. To add such extension to an existing classes, you have categories and extensions in Objective-C.

Declare Category in Objective-C

The @interface keyword is used in declaring categories in Objective-C. Here is the general form to declare categories in Objective-C. Here the name of the category is in parentheses:

@interface ClassName (CategoryName)

@end

Here are some characteristics of category in Objective-C:

  • A category can be declared for any class in Objective-C, even if you do not have any original implementation source code
  • At the program runtime, there is no difference between a method added by category and one that is implemented through original class
  • Any methods that you declared in category will be available to all the instances of original class, as well as any subclasses of the original class

Objective-C Category Example

Here is an example program, demonstrating category in Objective-C. Here is the sample category implementation. This program add a category to the Cocoa class NSString. This category will make it free for us to add a new method named get_copyright_string which helps in returning the copyright string.

/* Objective-C Category - Example Program */
		
#import <Foundation/Foundation.h>

@interface NSString(MyAdditions)
+(NSString *)get_copyright_string;
@end

@implementation NSString(MyAdditions)
+(NSString *)get_copyright_string
{
	return @"Copyright Codescracker.com 2015";
}
@end

int main(int argc, const char * argv[])
{
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	NSString *copyright_string = [NSString get_copyright_string];
	NSLog(@"Accessing Category = %@", copyright_string);
	[pool drain];
   
	return 0;
}

Now when we compile and run the above program, then we will get the following output:

2015-10-03 21:19:12.125 Categories[340:303] Accessing Category = Copyright Codescracker.com 2015

Objective-C Online Test


« Previous Tutorial Next Tutorial »