codescracker


objective c

Objective-C Category



« Previous Tutorial Next Tutorial »


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:

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

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test