objective c

Objective-C Extension

« Previous Tutorial Next Tutorial »

In Objective-C, a class extension contains some similarity to category, but it can only be added to class for which you have the source code at the compile time of the program (the class and the class extension is compiled concurrently.

The methods declared by class extension are simply implemented in the implementation block for original class, so you can not. For instance, declare a class extension on a framework class, such as Cocoa or Cocoa Touch class like NSString.

Declare Extension in Objective-C

The @interface keyword is used in declaring the extension in Objective-C. Here is the general form to declare an extension in Objective-C:

@interface ClassName ()


Objective-C Extension Example:

Here is an example program, demonstrates the concept of extension in Objective-C. Here this program create a class named MY_CLASS that has an extension. In the extension, have a private variable named internal_id. And then, have a method get_external_id that returns the externalID after processing internal_id:

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

@interface MY_CLASS : NSObject
	NSString *name;
- (void)set_internal_id;
- (NSString *)get_external_id;

@interface MY_CLASS()
	NSString *internal_id;

@implementation MY_CLASS
- (void)set_internal_id
	internal_id = [NSString stringWithFormat: 
- (NSString *)get_external_id
	return [internal_id stringByReplacingOccurrencesOfString: 
	@"UNIQUEINTERNALKEY" withString:@""];

int main(int argc, const char * argv[])
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	MY_CLASS *my_class = [[MY_CLASS alloc]init];
	[my_class set_internal_id];
	NSLog(@"External ID = %@",[my_class get_external_id]);        
	[pool drain];
	return 0;

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

2015-10-03 21:18:31.754 Extensions[331:303] External ID = 51

« Previous Tutorial Next Tutorial »

Latest 5 Posts by CodesCracker


Quick Links
Signup - Login - Give Online Test