开发者

iOS but why delegate

开发者 https://www.devze.com 2023-01-28 16:15 出处:网络
I see everywhere in iOS开发者_高级运维 programming that delegate is used....I am not sure what for is being used.

I see everywhere in iOS开发者_高级运维 programming that delegate is used....I am not sure what for is being used.

Can you please explain me about it?


When you need objects to behave differently from each other, you can either give them different implementations (often by subclassing, as is done with UIViewController), or by delegation. The difference is that polymorphism in the first case is achieved by making the objects of different type, whereas in the second, polymorphism is achieved by making objects of the same type delegate certain bits of functionality to objects of arbitrary type.

The reason people like delegation so much is that it allows a much cleaner class hierarchy: you don't need to subclass every little thing, just to respond to a few hooks. That's why we use delegation.

If you want to know the mechanics of delegation, and how to do it in your own classes, you're welcome to see my article Using custom delegates in Objective-C.


It's all just about optional function calls.

Objects can designed to optionally call methods in other objects. Some of those optional methods can be grouped together into a delegation pattern.

A delegate is simply another object that wants to be called by those methods. When you set a delegate, you let the calling object know that somebody wants to be called (accept the option), and who to call (the "delegate") whenever the option comes around.

If nobody wants to be the delegate, then the calling object with the option will usually just do some default behavior. So this pattern ("delegation") is a good way to be able to modify defaults, but not have to do so, and without requiring creating a lot of subclasses (which can get more confusing more quickly in the opinion of some people).

Here's another Stack Overflow answer about Delegates, I gave awhile back.

See Apple's Documentation on these design patterns.

0

精彩评论

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