views:

129

answers:

4

Like many people I'm interested on Objective - C and Cocoa programming. I know conceptually what a delegate it is but I don't understand how to use them or when to use them. Here is some example code:

#import "AppControler.h"


@implementation AppControler

-(id)init
{
    [super init];
    NSLog(@"init");

    speechSynth = [[NSSpeechSynthesizer alloc] initWithVoice:nil];
    //
    [speechSynth setDelegate:self];
    voiceList = [[speechSynth availableVoices] retain];

    return self;
}

I'm setting the AppControler to be the delegate of the speechSynthasizer. Which means that the speechSynthasizer is telling hte AppControler what to do. But I don't understand this line: [speechSynth setDelegate:self];

A: 

That's telling speechSynth that this particular instance of "AppControler" (which is misspelled) should be its delegate.

Azeem.Butt
+4  A: 

self is the current object, so [speechSynth setDelegate:self] sets the delegate of the speechSynth object to the current object, i.e. your AppControler (sic) instance.

Edit: In addition to the code shown, your AppControler should implement the NSSpeechSynthesizerDelegate protocol for the messages you wish to delegate to it.

Arkku
If you're familiar with other object-oriented languages like Java or C#, `self` in Objective-C means the same as `this` in those.
Arkku
"so [speechSynth setDelegate:self] sets the delegate of the speechSynth object to the current object, i.e. your AppControler (sic) instance."So the speechSynth object is being returned to the AppController?
lampShade
lampShade: No. The AppController already has the `speechSynth` object, because you gave it that object in the previous statement (where you assigned it to the `speechSynth` instance variable). The `setDelegate:` message does nothing but set the synthesizer's delegate.
Peter Hosey
+2  A: 

It means that speechSynth will send all of it's delegate messages to the instance of AppController

Instances of NSSpeechSynthesizer will send their delegates the message speechSynthesizer:didFinishSpeaking (make sure AppController implements this if you need to know when the speaking finishes)

For more general info on delegates check out Delegation

A: 

"Which means that the speechSynthasizer is telling hte AppControler what to do."

Really, the delegate usually does the telling.

An object with a delegate will ask the delegate wether or how it should do something, or inform the delegate about things it is about to do or has done. The delegate knows what to do, and the other object knows how to do them.

The delegate must implement the methods that the other object expects to call. For example, the delegate of a UIApplication generally implements applicationDidFinishLaunching: because the UIApplication knows how to launch but not what to do afterwards. Any class that takes a delegate will have a related protocol or category defining the methods that the delegate may implement.

drawnonward