Delegate in Cocoa

Delegate模式并没有标准定义,也没有标准行为,所以在不同的地方使用的方式也不一样,C#中Delegate就是一个方法,而Cocoa中Delegate是一个对象(或者说adopt了某个protocol的对象),下面的一句话描述还比较贴切:

A delegate is an object that’s given an opportunity to react to changes in another object or influence the behavior of another object.

It stores a reference to another object, its delegate, and sends messages to the delegate at critical times.The messages may just inform the delegate that something has happened, giving the delegate an opportunity to do extra processing, or the messages may ask the delegate for critical information that will control what happens.The delegate is typically a unique custom object within the Controller subsystem of your application.

很多Cocoa的类都支持Delegate模式,当然,每个类支持的Delegate需要adopt不同的protocol。比如NSWindow的Delegate需要adopt NSWindowDelegate;NSApplication的delegate需要adopt NSApplicationDelegate;

如何使用Delegate?

delegate的设置可以在IB中完成,也可以通过编程的方式完成。如果是在IB中完成,delegate就只能是custom object或者controller等其他存储在XIB中的对象;如果通过编程的方式实现,就没有这个限制了,只要能拿到这个对象的id,就可以作为delegate使用。

其他Delegate的例子:

NSTableView的delegate需要adopt NSTableViewDelegate;

NSTableView的dataSource(NSTableView的另外一个delegate)需要adopt NSTableViewDataSource protocol;

原文地址:https://www.cnblogs.com/whyandinside/p/2969828.html