7_Objective-C Protocols

  • Objective-C allows you to define protocols
  • To declare the methods expected to be used for a particular situation.
  • Protocols are implemented in the classes conforming to the protocol.

A syntax of protocol is shown below.

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

Here is the syntax for class conforming to protocol

@interface MyClass : NSObject <MyProtocol>
...
@end

This means that any instance of MyClass will respond not only to the methods declared specifically in the interface

But that MyClass also provides implementations for the required methods in MyProtocol.

There’s no need to redeclare the protocol methods in the class interface – the adoption of the protocol is sufficient.

If you need a class to adopt multiple protocols, you can specify them as a comma-separated list.

We have a delegate object that holds the reference of the calling object that implements the protocol.

Example

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: