开发者

setDelegate explanation

Hi i am new to iphone developement, can any one explain me why setDelegate i开发者_高级运维s used, where we should use it.

[request setDelegate:sender];

thanks in advance.


Delegates are simply a design pattern; there is no special syntax or language support.

A delegate is just an object that another object sends messages to when certain things happen, so that the delegate can handle application-specific details the original object wasn't designed for. It's a way of customizing behavior without subclassing.


Some classes, for example NSSpeechSynthesizer, include delegate support. Unlike a protocol, failure to provide a delegate method does not provoke an error: the class always provides a method, but calls yours instead, if it exists.

For example, NSSpeechSynthesizer has a method

-(void) speechSynthesizer:(NSSpeechSynthesizer*)sender 
        didFinishSpeaking:(BOOL)complete;

If you provide an identically declared method, in class Fred, it will be called instead of the synthesiser's own method, provided you have earlier done, in that class,

speech = [[NSSpeechSynthesizer alloc] initWithVoice:@"com.apple.speech.synthesis.voice.Albert"];

[speech setDelegate:self];

This will work, though the compiler will warn if you did not announce yourself as a delegate by

@interface Fred : NSObject <NSSpeechSynthesizerDelegate>, in that 
{

. . .

(This example is adapted from Cocoa Programming... by Hillegass).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜