If any top-level variables in a script contain Cocoa values, you lose persistence of globals. In script bundles and applets you can use NSUserDefaults to store values in a standard preference property list file.
In the case of a .scptd file, you need to initialize defaults with a suite name that matches the file’s bundle id, like this:
use framework "Foundation" use scripting additions set theDefaults to current application's NSUserDefaults's alloc()'s initWithSuiteName:(my id)
From then on you can simply read (using
objectForKey:) or write (using
setObject:forKey:) to your defaults.
For applets, it’s a bit trickier: applications normally use standarUserDefaults to access their defaults, but if you do that, when you edit and test you will be dealing with the preferences of the script editor, not the applet. You can cover all options like this:
use framework "Foundation" use scripting additions global theDefaults if my id = missing value then error "This code works only in an applet or script bundle." if current application's id = my id then -- must be running as applet set theDefaults to current application's NSUserDefaults's standardUserDefaults() else -- being run by editor or other host app set theDefaults to current application's NSUserDefaults's alloc()'s initWithSuiteName:(my id) end if
This approach will work for both applets and bundle files. Using a global variable lets you access the defaults object easily from anywhere in your script.
It is obviously very important to ensure your files have unique bundle ids.