Bir
Bir

Reputation: 812

When use protocol in objective-c?

Suppose Class1 and Class2 use same method method1. In that situation I can use protocol. Instead of protocol I can declare a super class called Superclass and implement method1 in that class. Now i can extend Class1 and Class2. After that I can use method1. So why I need protocol? and what is the advantage of using protocol?

Upvotes: 0

Views: 172

Answers (2)

Hussain Shabbir
Hussain Shabbir

Reputation: 15035

Protocols are used for sending the messages from one object to another. In addition to this it define a list of required and/or optional methods that a class implements. If a class adopts a protocol, it must implement all required methods in the protocols it adopts. Refer the below example when to use protocol:-

Consider you have one window which contains two ViewController class named as colorWellViewcontoller and chartReportViewController. Now colorWellViewcontoller class has one action method connected to the colorWell, which will trigger when user change the color. Now you want if color well color has been changed then same color should be applied in your chartReportViewController charts.

So in the above scenarios, You want to send the message e.g. color info to the another view controller whenever action method is called. So in this case you can use protocol.

Upvotes: 1

pjs
pjs

Reputation: 19855

Objective-C doesn't have multiple inheritance, but you can implement multiple protocols. Consequently, protocols give a contractual guarantee (which is checked by the compiler) that the class implements the desired methods, but without demanding that a particular ancestor class be in the inheritance chain.

Upvotes: 2

Related Questions