what are the Advantages of using protocols in Objective-C, when we require them? I have read the objective-C programming guide it shows mainly 3 advantages:
-
To declare methods that others are expected to implement.
-
To declare the interface to an object while concealing its class
-
To capture similarities among classes that are not hierarchically related.
Can any one explain me (2) and (3), I am not able to get it, as I have read details of them in Obj-C programming Guide? Are there any other advantages of using protocol? How can you describe why we need protocols in Objective-C?
2) To declare the interface to an object while concealing its class
and you using it like so in client code …
Notice how we are abstracted away from the actual database implementation and can run our query regardless of which database we’re talking with.
The advantage of defining
DatabaseConnectionas a protocol as opposed to a base class is that we don’t have to provide a default implementation. Because in this case, the default implementation would not make sense. A protocol is Objective-C’s way of doing a purely abstract base class in C++ or an interface in Java.3) To capture similarities among classes that are not hierarchically related.
You might want the ability to ask any object about which class it implements.
You might also want to know what its superclass is.
Perhaps you want to ask if any two objects are equal.
All of these things and more are methods you may want on classes such as File, MySQLConnection, User, MonsterX, MiniGun. Though these classes are entirely different from an inheritance point of view, which is why they can’t share a base class, a protocol addresses this need.
For example, Objective-C has a base protocol called NSObject.
Note: There will be some who point out that most Objective-C classes inherit from the NSObject class and that they get a number of these methods from there.
This statement is true. But
NSObjectthe class, implementsNSObjectthe protocol. Apple recognized that there will be cases when your objects do not inherit fromNSObjectthe class, but may still want to provide services such as responding to thedescriptionmethod.