Friday, February 1, 2013

Protocols in Objective C

Protocols are like interface in Java. It is having all methods. The implementation of the methods of this protocols are implemented in other class in which they are derived/subclassed.

Syntax / Protocols are declared as follows:-


@protocol NSObserver
- (void) response: (NSString *) str;
@end

When class is derived from protocol then that class must be implement all the methods of that protocol.

Deriving / adopting protocol 

@interface NSHttpRequest : NSObject < NSObserver , NSRequestSend >
{
// instance variables
}
// methods
@end 

You can specify the protocol name in the datatype like declaration or return type.
Example:-
id< NSObserver > obj;

It is telling that obj will hold anytime of object which has adopted NSObserver protocol.

There are two different types of methods in protocol.
i.Optional
ii. Required

When class derive/ adopted protocol need not compulsory to implements optional methods.
Required methods are compulsory to implement.
Method without any directive are compulsory to implement.

Ex:.

@protocol NSHttpObserver
- (void) response: (NSString *) str;// compulsory to implement
@optional 
-(NSString*) getHeader; // optional to implement

@required
- (void)setUri(NSString*) uri;// compulsory to implement
- (void)setProxy(NSString*) proxy;// compulsory to implement


@end // BaseballPlayer









0 comments:

Post a Comment

About

Powered by Blogger.