codescracker


objective c

Objective-C Protocol



« Previous Tutorial Next Tutorial »


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
// required methods list
@optional
// optional methods list
@end

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>
...
@end

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;
@end

@interface PRINT_CLASS :NSObject
{
	id delegate;
}
- (void) PRINT_DETAILS;
- (void) setDelegate:(id)newDelegate;
@end

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

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

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

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

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test