What is protocol?
Protocol is a concept of sharing the same methods and property declarations among the classes without inheriting them from a common ancestor.
A protocol is simply a grouping of certain related methods under one name, and
A protocol, declared with the (@protocol syntax in Objective-C) is used to declare a set of methods that a class "adopts" (declares that it will use this protocol) will implement.
Swift 2 Tutorial Part 2: Basics
To define methods that are to be implemented by other classes.
Suppose, particular class only has one parent, and its parent has one parent, and so on right up to the root object (NSObject).
But what if your class needs to call methods on objects outside of its parent tree?
A protocol is one way to solve this problem.
To declare the public interface to a class while hiding the nature of the class itself.
To mark similarities between classes that are not part of the same inheritance tree.It lets you avoid the complexities of subclassing, similar to the way categories do, but in a different manner.
some key concepts for an iPhone developer to learn as a fresher
What are best practices that you use when developing projects in Objective-C ?
Syntax for declaring a protocol
@required // list of required methods
@optional // list of optional methods
Types of Protocols
There are two types of protocol basically used in Objective C
- Formal protocol
- Informal protocol
An informal protocol is a category on NSObject, which implicitly makes almost all objects adopters of the protocol.
A category is a language feature that enables you to add methods to a class without subclassing it.
Implementation of the methods in an informal protocol is optional. Before invoking a method, the calling object checks to see whether the target object implements it.
A UITableView requires a data source and a delegate object.
These must conform to the UITableViewDataSource and UITableViewDelegate protocols.
What are required delegates and data sources for Table View?
To adopt a protocol, add it to your class header file.
@interface MyViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
The protocol names appear after the class declaration, inside angled brackets. When adopting more than one protocol, list them in a comma-separated list.
Then in your implementation (.m) file,implement all of the required methods for each protocol.
What is "Optional" ?
Some protocol methods can be marked as optional. This means you don't have to implement those.
A delegate allows one object to send messages to another object when an event happens.
Create Your Own Objective-C Delegate Protocol
For easy understanding I am sharing an example which includes protocol and delegate .
Here,the instance variable delegate is of type id, as it will be unknown at compile time the type of class that will adopt this protocol.