Dr.Kameleon
Dr.Kameleon

Reputation: 22810

How to handle Cocoa application termination properly?

So, here's my case :

I'm developing a NON-standard document-based application and I want to handle the scenario of aborting the termination when there still are unsaved changes in any of the documents.

My initial idea is :

So, I decided to do it the delegate-way.

In my Application delegate, I've implemented :

Now, that's what I'm thinking. In the applicationShouldTerminate: method :

Is that the right way to go about it?

Any suggestions?

Upvotes: 2

Views: 2276

Answers (1)

Frederik Slijkerman
Frederik Slijkerman

Reputation: 6529

That's indeed how to do it. But in your applicationShouldTerminate implementation, you should just pop up the alert right there, and return NSTerminateNow if the user didn't click Cancel; NSTerminateCancel otherwise. No need to manually terminate the application later.

Edit: to show an alert as a sheet but run it as a modal dialog, call beginSheetModalForWindow on the alert, then call [NSApp runModalForWindow:alert]. In addition, in the end selector that you pass for beginSheetModalForWindow, you need to call [NSApp stopModal] to get out of the modal loop.

However, it is better in this case to run the alert as a sheet for the window, and return NSTerminateLater in your applicationShouldTerminate implementation. Then, in the end selector for the alert, call [NSApp replyToApplicationShouldTerminate:]. This is how Apple recommends you implement this.

Upvotes: 7

Related Questions