title: How do I run code when a user agent process terminates?
body: <p><strong>What I want</strong></p>
  
  <p>I want a helper app user agent (LSUIElement in Info.plist is True) to add itself to the login items on terminate.</p>
  
  <p><strong>The Problem</strong></p>
  
  <p>I can't get any code to run before the helper app process terminates.
  My "add to login items" code runs fine.</p>
  
  <p><strong>Background</strong></p>
  
  <ul>
  <li>I've got a helper app user agent process that runs all the time</li>
  <li>On first launch, it adds itself to login items</li>
  <li>If the app was moved, on next login, the helper app process can't be found and so isn't launched</li>
  </ul>
  
  <p><strong>What I've Tried</strong></p>
  
  <p>I wonder if I should subclass NSApplication and override terminate: or stop: and put my code in there, but that seems overkill. Surely there's a better way?</p>
  
  <p>I've tried all these different things in the NSApp delegate:</p>
  
  <pre><code>-(void)applicationWillTerminate:(NSApplication *)sender {
       [self addHelperAppToLoginItems]
  }
  
  -(void)applicationDidTerminate:(NSApplication *)sender {
       [self addHelperAppToLoginItems]
  }
  
  -(NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
       [self addHelperAppToLoginItems]
  }
  
  -(void)applicationDidFinishLaunching:(NSNotification *)aNotification {
       [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self 
                                                              selector:@selector(addHelperAppToLoginItems) 
                                                                  name:NSWorkspaceDidTerminateApplicationNotification
                                                                object:nil];  
  
  }
  
  -(void)addHelperAppToLoginItems {
        // This code never gets called!
  }
  </code></pre>
  
  <p>Why do the NSApplication delegate methods not work with a user agent process? </p>
  
  <p>And how can I get the process to check the login items on terminate?</p>
  
  <p>I'd be very grateful for any help. Thanks!</p>
  
  <p><strong>UPDATE 1 6/2/11</strong></p>
  
  <p>After some further digging, the problem is more that processes never really get quit, it's more common for them to get killed by the OS.</p>
  
  <p>This means when you choose to "Quit" a process in Activity Monitor or you shut down the computer, the terminate delegate methods don't get called. </p>
  
  <p>When the following Applescript is run, the delegate methods do get called:</p>
  
  <pre><code>tell application "System Events"
      tell application "LapsusHelperApp"
           quit
      end tell
  end tell
  </code></pre>