一个代表如何在客观C中工作? [英] How does a delegate work in objective-C?

查看:90
本文介绍了一个代表如何在客观C中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 有没有人知道在哪里可以找到一个很好的解释/教程应用程序委托在 objective-C 中的工作原理?

  2. 这两本书,我不会在代表中留下足够的代价,并没有很好的解释他们真正了解他们的权力并且功能。


解决方案

如有疑问,请查看 docs



基本上,委托是允许对象彼此交互而不在其间创建强大的相互依赖关系的方式,因为这样使您的应用程序的设计变得更加灵活。而不是彼此控制的对象,它们可以具有它们发送(或委派)消息的代理,并且委托执行任何操作,以便响应并对该消息执行操作,然后通常返回到另一个对象。



委托也是子类化的更好的替代方案。而不是您必须创建自己的自定义类来稍微改变其他对象的行为方式或传递它们的数据,委派允许对象向他们的代理发送消息,为他们做工作,而不需要创建子类来进行微小的更改当然,委托的主要缺点是可用的委托方法取决于苹果工程师预见的有用的方式,以及他们期望的共同实现方式需要,这限制了你可以实现什么。尽管Quinn Taylor指出,这是特定于Cocoa框架的,因此不适用于所有情况。



如果委托是子类化的选项,那么请这是因为它是一种更清晰的方式来管理您的代码和对象之间的交互。


  1. Does anyone know where I can find a good explanation/tutorial of what and how an application delegate works in objective-C?
  2. The two books I have don't dwell on delegates enough and do not explain them very well for me to truly understand their power and function.

解决方案

When in doubt, check the docs!

Basically, delegation is a way of allowing objects to interact with each other without creating strong interdependencies between them, since this makes the design of your application less flexible. Instead of objects controlling one another, they can have a delegate which they send (or delegate) messages to, and the delegate does whatever they do, in order to respond and act to this message, and then usually return something back to the other object.

Delegation is also a better alternative to subclassing. Instead of you having to create your own custom classes to slightly alter the way that other objects behave, or pass them data, delegation allows objects to send messages to their delegates to do work for them without the overhead of creating subclasses to make minor changes to other objects.

Of course, the main disadvantage of delegation is that the delegate methods available are dependent on what the Apple engineers foresee as being useful and what common implementations they expect people to need, which imposes a restriction on what you can achieve. Although, as Quinn Taylor pointed out, this is specific to the Cocoa frameworks and so doesn't apply in all situations.

If delegation is an option over subclassing, then take it, because it's a much cleaner way to manage your code and interactions between objects.

这篇关于一个代表如何在客观C中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆