Why would I want to use a protocol rather than create a subclass and inherit the methods..?
Please explain it to me, i'm to confused about this topic, i'm not very pleased with the explanation in the book im reading.
Where do I use protocols instead of other ways to get the methods..? if I can subclass a class and get the methods why would i want to use a protocol where i need to define the methods?
Why would I want to use a protocol rather than create a subclass and inherit the methods..?
Protocols make it possible for unrelated classes to all implement the same interface. Instances of each of those classes can then be used by a client of the protocol. For example, UITableViewDataSource
is a protocol that provides an interface by which a table can ask for data from any object that implements the protocol. The table view doesn't care what the type of the object is so long as it implements the data source interface.
Imagine how unpleasant things would be if all table data sources had to inherit from a common class! Objective-C only provides single inheritance, so you'd effectively be constrained to using only a single kind of object for your data source. With protocols, though, a data source can be a view controller, a model object, or perhaps even a remote object.
To be more specific, protocols allow a form of polymorphism. That means that a single object can take several forms: e.g. view controller, table data source, table delegate, scroll view delegate. Because Objective-C is a single-inheritance language, you only get one of those interfaces via inheritance. The rest you implement yourself, but that often makes sense because you generally adopt a given protocol in order to customize some other object's behavior anyway.