开发者

Delegate vs Protocol [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

Difference between protocol and delegates?

Is there any difference between Protocol and Delegates?

If they are same why do we need two doing the same?

When to use Delegate and 开发者_高级运维when to use Protocol.

I am new to Objective-C and Iphone programming. So please bear with me.


Protocols and delegates are two related but different concepts:

On the one hand, protocols declare methods that can be implemented by any class. These classes are said to conform to the protocol. They are like interfaces in Java. Protocols can be formal or informal:

  • Formal protocols are declared with a @protocol block.

  • Informal protocols can be implemented in terms of a @protocol block with all the methods being @optional or with a category of NSObject.

On the other hand, delegation is a design pattern by which an object is given an opportunity to react to changes in another object or influence its behaviour. The basic idea is to get two objects to coordinate to solve a problem while minimizing coupling between these two objects and avoiding subclassing. Subclassing creates a tight coupling between the subclass and its superclass whereas delegation creates a much looser relationship based on anonymous objects.

This pattern is typically implemented by the means of a protocol or to put it in another way, a delegate is typically an anonymous object that conforms to a protocol.


A protocol is an interface that a class can conform to, meaning that class implements the listed methods. A class can be tested for conformance to a protocol at compile-time and also at run-time using the conformsToProtocol:.. NSObject method.

A delegate is a more abstract term that refers to the Delegation Design Patten. Using this design pattern, a class would have certain operations that it delegates out (perhaps optionally). Doing so creates an alternative to subclassing by allowing specific tasks to be handled in an application-specific manner, which would be implemented by a delegate.

They are related terms because you often see a Protocol created for the purpose of delegation. If I wanted to allow a delegate to sort something, I'd create a Protocol with a required method listed such as "sortMyCoolStuff:.." and I would require the delegate to implement it. That way, within class that supports calling to a delegate, I can accept a pointer to a delegate and then can say "if that delegate conforms to myCoolProtocol, I know it implements sortMyCoolStuff, so it's safe to call that method instead of doing my built in behavior"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜