title: Cocoa and AppleScript / Apple Events
body: <p>I'm using Cocoa’s <code>[[NSWorkspace sharedWorkspace] launchApplicationAtURL…</code> with the <code>NSWorkspaceLaunchNewInstance</code> option to spawn new instances of an AppleScriptable application (Adobe Acrobat), and I want to be able to trigger different Apple Events (do script, quit, save etc…) for each instance.</p>
  
  <p>So far I’ve tried to AppleScript ”System Events” and <code>tell</code> commands based on a new process’ id but for some reason the commands aren't executed by the target process. </p>
  
  <p>I'm getting the process id as <code>[NSRunningApplication processIdentifier]</code> and use that to compile an applescript by <code>[[[NSAppleScript alloc] initWithSource: AppleScript] executeAndReturnError: nil]</code>. The string representation of the AppleScript is something like the following:</p>
  
  <pre><code>tell application "System Events"
    tell (process id [insert process id here]) to do script "this.preflight(Preflight.getProfileByName('Magazine Ads'),false,false);"
  end tell
  </code></pre>
  
  <p>I'm suspecting that the <code>processIdentifier</code> returned by <code>NSRunningApplication</code> is different from the process id used by ”System Events”, but I'm stuck and don't know where to look to get any further. I need a pointers on how to trigger AppleScriptable methods of specific application process from Cocoa, given that </p>
  
  <ul>
  <li>there can be several instances of the same application running and</li>
  <li>each process that I want to communicate with will be created within the scope of my code</li>
  </ul>
  
  <p>(Running new processes of Adobe Acrobat is necessary to allow the user to do other work while a preflight is running.)</p>
  
  <hr>
  
  <p>Edit: The process id returned by cocoa and AppleScript are different:</p>
  
  <pre><code>tell application "System Events" to set process_id to id of every process whose name contains "AdobeAcrobat"
  </code></pre>
  
  <p>returned {5584211,…}, while at the same time</p>
  
  <pre><code>[NSRunningApplication processIdentifier]
  </code></pre>
  
  <p>returned 8722 </p>
  
  <hr>
  
  <p>Edit 2: The AppleEvent object does make it possible to address a process with a certain process id but I haven't been able to figure out how to apply it to an AppleScript object.</p>
  
  <pre><code>pid_t process_id = …; 
  NSAppleEventDescriptor* appleevent = [[NSAppleEventDescriptor alloc] initWithDescriptorType:typeKernelProcessID bytes:&amp;process_id length:sizeof(pid)];
  </code></pre>
  
  <p>I still haven't figured out how <code>NSAppleEventDescriptor</code> be used to access AppleScriptable methods of a process with the given <code>process_id</code>. Any pointers to resources and possibly an example of this would be a perfectly answer to my question.</p>