Catching Logoff (not power off) event on MAC using objective C Catching Logoff (not power off) event on MAC using objective C unix unix

Catching Logoff (not power off) event on MAC using objective C


First, you have to make sure your app is not participating in sudden termination. If it is, then it can be killed at logout without any opportunity to react.

Now, when the user logs out, your app will get a kAEQuitApplication ('quit') Apple Event. This will have the same effect as an invocation of -[NSApplication terminate:]. You can implement the application delegate method -applicationShouldTerminate: to be notified of the request to quit and control your app's response to it.

In that delegate method, you can use code like this to examine the quit event and learn the reason for the quit request:

    NSAppleEventManager* m = [NSAppleEventManager sharedAppleEventManager];    NSAppleEventDescriptor* desc = [m currentAppleEvent];    switch ([[desc attributeDescriptorForKeyword:kAEQuitReason] int32Value])    {        case kAELogOut:        case kAEReallyLogOut:            // log out            break;        case kAEShowRestartDialog:        case kAERestart:            // system restart            break;        case kAEShowShutdownDialog:        case kAEShutDown:            // system shutdown            break;        default:            // ordinary quit            break;    }