6

I implemented applicationWillTerminate method, but it's never called

-(void)applicationWillTerminate:(NSNotification *)notification
{
    [[NSApplication sharedApplication] terminate:self];
    NSLog(@"EOP");
}

How to execute some code before application close?

Thanks

Ilya Blokh
  • 11,923
  • 11
  • 52
  • 84

3 Answers3

5

I just added

-(BOOL) applicationShouldTerminateAfterLastWindowClosed:(NSApplication *) sender{
return YES;
}

Now applicationWillTerminate invokes

Borzh
  • 5,069
  • 2
  • 48
  • 64
Ilya Blokh
  • 11,923
  • 11
  • 52
  • 84
  • 1
    If this changes it, then perhaps the app wasn't actually closing? You were just closing all the windows of the app? – Jesse Rusak Nov 19 '11 at 17:37
  • Most likely you're right. But now app closes: I got that I needed – Ilya Blokh Nov 19 '11 at 17:53
  • 2
    It isn't possible to close an application; that verb doesn't go with that noun. And yes, an application ordinarily does not automatically quit when the user closes its last window; you must opt into that. Actually quitting the application with the Quit command will always trigger `applicationWillTerminate:` (assuming nothing, such as a confirmation alert, gets in the way). An alternative introduced in Lion is Automatic Termination, which is lazier and pretends the app is still running; see the docs. – Peter Hosey Nov 19 '11 at 19:14
  • How does this even work when you defined function as returning nothing but you return bool? – Morteza Milani Jul 03 '12 at 16:27
  • Of cause it's misprint) fixed – Ilya Blokh Jul 25 '12 at 11:19
  • This just tells your app that it should quit automatically when there is no more opened window. It is not really related to the 'applicationWillTerminate never called' problem – Moose Nov 22 '20 at 07:08
3

Solution 1:

Set the Application can be killed immediately to NO in the project info ( NSSupportsSuddenTermination key ). The applicationWillTerminate function will then be called before the application quits.

Solution 2:

If you need to be able to cancel the termination, then you should rather override the applicationShouldTerminate function

func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
    // Do some stuff before quitting for good
    return .terminateNow
}
Moose
  • 2,607
  • 24
  • 23
0

please set a key (UIApplicationExitsOnSuspend) in your plist to YES.

Key : UIApplicationExitsOnSuspend
Type : Boolean
Value :YES

Sangram Shivankar
  • 3,535
  • 3
  • 26
  • 38
Vicky
  • 1,095
  • 16
  • 15