Objective-C Protocol

You are free to define protocols in Objective-C, which declare the methods expected to be used for certain situation. Protocols are implemented in the classes conforming to protocol.

For instance, a network URL handling class, it will have a protocol with the methods like processCompleted delegate method that intimates the calling class when the network URL fetching operation is completed. Here is the general form of protocol in Objective-C:

@protocol ProtocolName
// required methods list
// optional methods list

Here, the methods under the keyword @required must be implemented in the classes which conforms to the protocol and the methods under the @optional keyword are optional to implement. Here is the general form for class conforming to the protocol:

@interface SAMPLE_CLASS : NSObject <MY_PROTOCOL>

It means that any instance of SAMPLE_CLASS will respond not only to the methods declared specifically in the interface, but SAMPLE_CLASS also provides the implementations for the required methods in MY_PROTOCOL. And there is no need to re-declared the protocol methods in the class interface.

Objective-C Protocol Example

Here is an example program, demonstrates the concept of protocol in Objective-C:

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

@protocol PrintProtocolDelegate
- (void)processCompleted;

@interface PRINT_CLASS :NSObject
	id delegate;
- (void) setDelegate:(id)newDelegate;

@implementation PRINT_CLASS
	NSLog(@"Printing Details");
	[delegate processCompleted];
- (void) setDelegate:(id)newDelegate
	delegate = newDelegate;

@interface SampleClass:NSObject<PrintProtocolDelegate>
- (void)startAction;

@implementation SampleClass
- (void)startAction
	PRINT_CLASS *print_class = [[PRINT_CLASS alloc]init];
	[print_class setDelegate:self];
	[print_class PRINT_DETAILS];
	NSLog(@"Printing Process Completed");

int main(int argc, const char * argv[])
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	SampleClass *sampleClass = [[SampleClass alloc]init];
	[sampleClass startAction];
	[pool drain];
	return 0;

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

2015-10-03 21:15:50.362 Protocols[275:303] Printing Details
2015-10-03 21:15:50.364 Protocols[275:303] Printing Process Completed

Objective-C Online Test

« Previous Tutorial Next Tutorial »