Closing the window when speech is finished

In the “Implementing another delegate” section, the book states this:

I fed my SpeakLine app a long string and clicked the red stoplight button while it was speaking, but the window did not close when the speech finished. Should it actually close under these circumstance? And thus, am I doing something wrong? The only solution I could think of was to assign some kind of closeWhenFinished variable to true in the windowShouldClose function, and then check that in the didFinishSpeaking function and close it programmatically, but that seems a bit tedious. I’m just wondering if I’ve overlooked something.

It sounds like you have the right idea about what is going on by the latter portion of your post. What the book is saying is more along the lines of, “The window will only close if the speech synthesizer has stopped speaking.” Our wording could have been more precise here.

To implement it as it sounds, yes, you would need to store some sort of state and then check that state in didFinishSpeaking.

I finally figured out what you meant by the “red stoplight button”: the red X that a user clicks on to close a window! I was looking around Xcode for some type of color scheme that displayed a red stop sign.

By the way, Cocoa uses a naming convention like this:

somethingWillClose() somethingShouldClose() somethingDidClose()

The “Will” functions tell you when an event, in this case “Close”, is about to happen, so if you need to do something before the event happens, you implement that function.

The “Did” functions tell you when an event just occurred, so if you need to do something after the event occurred, you implement that function. One example of such a function that we’ve seen already in the book is: windowDidLoad().

The “Should” functions tell you that an event is about to happen–just like with the “Will” functions–but with the “Should” functions you can cancel the event. The “Should” functions are defined to return a Bool, i.e. true or false, and if you return false, then the event will be cancelled. In contrast, the “Will” and “Did” functions are not defined to return anything, so when you implement one of those functions, you do not have the opportunity to return false to cancel the event.

In SpeakLine, you are told to implement:

and the return statement looks like this:

When isStarted is true, i.e. the SpeechSynthesizer is speaking, then the function returns !true, which is the same as false–which cancels the event.

Every time you click on the red X to close the window, Cocoa calls windowShouldClose(:slight_smile: again, and if windowShouldClose(:slight_smile: returns false, then the “close the window” event is cancelled. You can think of it this way: the “Should” functions are asking you a question, “windowShouldClose?” And by returning true or false, you are answering the question.