TweetFollow Us on Twitter

Storing and Accessing Data with AppleScript

Volume Number: 22 (2006)
Issue Number: 3
Column Tag: Programming

AppleScript Essentials

Storing and Accessing Data with AppleScript

by Benjamin S. Waldie

In last month's column, I provided an introduction to Database Events, a new technology that made its debut with Mac OS X Tiger. I discussed how Database Events can be used as a method of data storage and retrieval by allowing AppleScript to interact directly with SQLite databases.

In this month's column, I would like to discuss some other methods of storage and retrieval, such as accessing properties directly within scripts, or within property list files in the operating system.

Script Properties

The first mechanism for data storage that I would like to address is a script property. When scripting an application, many times, a class within that application will possess properties, or attributes that are accessible through AppleScript. For example, in the Finder, the disk class possesses a number of properties, including a name, capacity, and format. When writing a script, you can define properties for your script itself. A script property is defined within a script using the following syntax:

property propertyName : "Property Value"

For example:

property theUserName : "bwaldie"

Script properties may be defined anywhere within the top level of a script (or a script object). Once a property has been defined, it becomes global in nature, and is accessible both throughout the top level of the script, as well as throughout any handlers in the script.

When a script property is defined, its value is officially assigned when the script is compiled. This means that there is no need to define a value for the property, as you would a variable, within your script's executable code. Rather, you may immediately begin referring to the property.

Script properties are accessible in the same way that variables are accessible. You may get the value of a property and you may set the value of a property in the same way that you would do with a variable. Unlike local variables, however, properties are global in nature. This means that the property is accessible at any level of a script - at the top level, and also within any handlers. For example, after defining the property in the previous example code, the following code would be valid executable code at any level of the script, and would not generate an error indicating that propertyName is not defined.

display dialog propertyName

Properties also retain their most recent values between script executions, and will continue to do so until the script is recompiled. This makes properties an ideal mechanism for storing and retrieving data, so long as the script does not need to be frequently recompiled.

Working with a Property in a Script

Let's take a look at a property in action. The following example code demonstrates how a property can be used to store a persistent value between script executions.

property theRunCount : 0

set theRunCount to theRunCount + 1
display dialog "This script has been run " & theRunCount & " time(s)."

If you run the previous code in Script Editor, the first time the script is run, a dialog will be displayed indicating that the script has been run one time. If you then run the script again, the dialog will indicate that the script has been run two times. If you run it again, the dialog will indicate that the script has been run three times. This will continue indefinitely until the script is recompiled. If you do recompile the script and run it again, the script will start over, indicating that it has been run one time.

To quickly recap what is occurring in this code, the first line of the script defines a property, named theRunCount. The second line changes the value of the property by incrementing its value by one. The third line displays a dialog message that includes the new property value. This new property value is then retained by the script until the next execution, when it is incremented again. When the script is recompiled, the original value of 0 is re-assigned to the property.

Properties are a great way to store information such as commonly requested file or folder paths, usernames, run counts, last execution dates, and more.

    IMPORTANT: Please be aware that properties that are assigned in AppleScript Studio projects are NOT persistent between script executions.

Working with a Property in Another Script

Now that we have discussed storing and accessing properties within a script, let's take the concept one step further - storing and accessing properties in another script. First, create a new document in Script Editor, and enter the following code:

property theRunCount : 0

Next, save the script to the desktop, and name it Properties.scpt. Now, create a new Script Editor document, and enter the following code:

set thePropertyScriptPath to (path to desktop folder as string) & "Properties.scpt"
set thePropertyScript to load script file thePropertyScriptPath
set thePreviousRunCount to (theRunCount of thePropertyScript)
set theNewRunCount to thePreviousRunCount + 1
set theRunCount of thePropertyScript to theNewRunCount
store script thePropertyScript in file thePropertyScriptPath with replacing
display dialog "This script has been run " & theNewRunCount & " time(s)."

Now save this second script to the desktop, and name it External Run Count.scpt. See figure 1.


Figure 1. Accessing a Property from an External Script

If you run the External Run Count.scpt script multiple times, you will encounter behavior similar to that of my earlier examples. The script will display a dialog indicating how many times the script has been triggered. However, this value is not being stored internally. Rather, it is being stored externally in another script.

In the example above, the external script, Properties.scpt, is being loaded by the script External Run Count.scpt. The value of the property theRunCount is being retrieved, and changed within the loaded script. The modified loaded script is then being stored back into its original file, for the next execution.

There are many benefits to utilizing properties in this manner. Let's say, for example, that you have a script that you have created and saved as a run-only application. However, you want others to have the ability to change certain behavioral aspects of that script. You could create properties that control those behaviors, and store them in a separate, editable script. Then, your main script could load and access those properties as needed, during execution. I use this technique frequently when delivering scripts that may not have configurable user interfaces to clients. While the main code of my script may be locked, the client usually has the ability to change certain aspects of how the script behaves by modifying properties in an external script "settings" file.

Property List Files

The next mechanism that I would like to discuss for data storage and retrieval is property list files in Mac OS X, a.k.a. pList files. Property list files are XML-based files, which are utilized by many applications and processes in Mac OS X for storing and retrieving information.

In the past, I have mentioned an application named System Events, which is located in the System > Library > CoreServices folder in Mac OS X. System Events is a background application, which provides scriptable access to many aspects of Mac OS X. With the release of Mac OS X Tiger, Apple has introduced a new suite of terminology into the System Events application - a Property List Suite. See figure 2.


Figure 2. System Events' Property List Suite

The Property List Suite in System Events provides AppleScript with a way to retrieve and modify values within property list files.

Creating a New Property List File

Before getting started with the actual scripting terminology, let me first mention creating property list files. Unfortunately, at present, System Events does not provide a way to create property list files via AppleScript. The intention at this point is to provide a way for scripters to interact with existing property list files.

That said, inevitably, AppleScripters want the ability to create property list files. So, until that functionality is built into System Events (assuming it will be at some point in the future), here is some example code for creating a basic property list file with AppleScript. The code below will write the base XML of an empty property list file to a new text file on the desktop. Feel free to adjust this code as needed in order to meet your specific needs.

set theEmptyPListData to "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
<plist version=\"1.0\">
<dict/>
</plist>"

set theOutputFolder to path to desktop folder as string
set thePListPath to theOutputFolder & "myPListFile.plist"
set thePListFile to open for access thePListPath with write permission
set eof of thePListFile to 0
write theEmptyPListData to thePListFile starting at eof
close access thePListFile

Adding New Properties to a Property List File

If you need to generate property list files through scripting, then you probably also need the ability to add new properties to those files. Again, I'm sorry to say that, unfortunately, this is not the most straight-forward process with System Events. As mentioned previously, System Events is intended to provide a way for you to be able to access and modify existing properties. At present, it is not really intended for creating property list files or adding new properties. However, there is a way to do it, and here it is.

In System Events, the Property List Suite consists of two classes, a property list file and a property list item. The property list file class has a contents property, which consists of a property list item class. This property list item class possesses kind, name, and value properties. Out of these, value is the only modifiable property. To add a new property list item within the contents of a property list file, you need to set the value of this property list item to an AppleScript record. This AppleScript record must consist of one or more field names and values, which correspond to XML keys and values, respectively. For example:

set theOutputFolder to path to desktop folder as string
set thePListPath to POSIX path of (theOutputFolder & "myPListFile.plist")
tell application "System Events"
   tell property list file thePListPath
      tell contents
         set value to {|keyName|:"keyValue"}
      end tell
   end tell
end tell

After running the code above, a new property would be generated as XML within the referenced property list file, and would appear as follows:

<dict>
   <key>keyName</key>
   <string>keyValue</string>
</dict>

You can also use a similar technique to add to property list files that already contain existing properties. The following example code demonstrates how this can be done.

set theOutputFolder to path to desktop folder as string
set thePListPath to POSIX path of (theOutputFolder & "myPListFile.plist")
tell application "System Events"
   tell property list file thePListPath
      tell contents
         set previousValue to value
         set value to (previousValue & {|keyName2|:"keyValue2"})
      end tell
   end tell
end tell

In the example code above, first, the existing value of the property list file's content is retrieved. Next, a new AppleScript record is appended to that value. The revised value is then reapplied to the property list file. The resulting XML of the property list file appears as follows:

<dict>
   <key>keyName</key>
   <string>keyValue</string>
   <key>keyName2</key>
   <string>keyValue2</string>
</dict>

In the previous two examples, I have demonstrated how to create property list items that contain string values. There are other types of values that can be created in property list files, including booleans, dates, lists, records, etc. Here, is another example of code that will append a new property to a property list file. This time, a record will be added.

set theOutputFolder to path to desktop folder as string
set thePListPath to POSIX path of (theOutputFolder & "myPListFile.plist")
tell application "System Events"
   tell property list file thePListPath
      tell contents
         set previousValue to value
         set value to (previousValue & {|keyName3|:{subKeyName1:"subKeyValue1", 
            subKeyValue2:"subKeyValue2"}})
      end tell
   end tell
end tell

The above example code would change the contents of the property list file to appear as follows:

<dict>
   <key>keyName</key>
   <string>keyValue</string>
   <key>keyName2</key>
   <string>keyValue2</string>
   <key>keyName3</key>
   <dict>
      <key>subkeyname1</key>
      <string>subKeyValue1</string>
      <key>subkeyvalue2</key>
      <string>subKeyValue2</string>
   </dict>
</dict>

Modifying Properties in a Property List File

Once properties exist within a property list file, the values of these properties may be modified using System Events. The following example code demonstrates how to modify the value of a property that was created in the previous example:

set theOutputFolder to path to desktop folder as string
set thePListPath to POSIX path of (theOutputFolder & "myPListFile.plist")
tell application "System Events"
   tell property list file thePListPath
      tell contents
         set value of property list item "keyName" to "New Key Value"
      end tell
   end tell
end tell

Once the specified property has been modified, its new value will be reflected immediately in the property list file. For example:

<dict>
   <key>keyName</key>
   <string>New Key Value</string>
   <key>keyName2</key>
   <string>keyValue2</string>
   <key>keyName3</key>
   <dict>
      <key>subkeyname1</key>
      <string>subKeyValue1</string>
      <key>subkeyvalue2</key>
      <string>subKeyValue2</string>
   </dict>
</dict>

Likewise, property list items contained within other property list items may also be modified. In doing so, you must be sure to refer to these property list items within their proper containment hierarchy. The following example code demonstrates how to change the value of a property list item within another property list item.

set theOutputFolder to path to desktop folder as string
set thePListPath to POSIX path of (theOutputFolder & "myPListFile.plist")
tell application "System Events"
   tell property list file thePListPath
      tell contents
         set value of property list item "subKeyName1" of property list item 
            "keyName3" to "New Key Value"
      end tell
   end tell
end tell

After running the previous code, the property list file's content would appear as follows:

<dict>
   <key>keyName</key>
   <string>New Key Value</string>
   <key>keyName2</key>
   <string>keyValue2</string>
   <key>keyName3</key>
   <dict>
      <key>subkeyname1</key>
      <string>New Key Value</string>
      <key>subkeyvalue2</key>
      <string>subKeyValue2</string>
   </dict>
</dict>

Retrieving Properties From a Property List File

As you might expect, retrieving a property value from a property list file is relatively straightforward. For example:

set theOutputFolder to path to desktop folder as string
set thePListPath to POSIX path of (theOutputFolder & "myPListFile.plist")
tell application "System Events"
   tell property list file thePListPath
      tell contents
         value of property list item "keyName"
      end tell
   end tell
end tell
--> "New Key Value"

One thing that I do want to stress is, when working with property list files, you do not need to access only property list files that you have created. You may actually use System Events to retrieve and/or modify the values of the property list files of other applications or processes.

For example, the code below demonstrates how to retrieve the value for one of Safari's preferences. In particular, this code will retrieve the value of the AlwaysShowTabBar preference, which indicates whether the tab bar should be displayed in Safari.

set thePListFolderPath to path to preferences folder from user domain as string
set thePListPath to thePListFolderPath & "com.apple.Safari.plist"

tell application "System Events"
   tell property list file thePListPath
      tell contents
         value of property list item "AlwaysShowTabBar"
      end tell
   end tell
end tell
--> true

Storing Properties in an AppleScript Studio Project

Next, I'd like to touch briefly on AppleScript Studio. Earlier, I mentioned that AppleScript Studio does not have the ability to store persistent property values between script executions. However, in many cases, this may not be necessary anyway. The reason for this is because AppleScript Studio actually provides terminology for accessing properties in the application's property list file directly. This is done by accessing the user defaults class of the application class, which may contain default entry classes as elements. These default entry classes may be created and modified within the context of the user defaults class as needed during the execution of your script. Once the application quits, any default entries will be written to the property list file for the application, where they will be accessible the next time the application runs.

The following example code demonstrates how user defaults and default entries may be used to store information.

on launched theObject
   if (default entry "theRunCount" of user defaults exists) = false then
      make new default entry at end of default entries of user defaults with 
      properties {name:"theRunCount", contents:0}
   end if
   idle
end launched

on idle
   set theRunCount to contents of default entry "theRunCount" of user defaults
   set theNewRunCount to theRunCount + 1
   display dialog "This script has been run " & theNewRunCount & " time(s)."
   set contents of default entry "theRunCount" of user defaults to theNewRunCount
   quit
end idle

In the on launched handler above, an if statement is used to determine whether a default entry named theRunCount already exists in the user defaults. If it does not, then it is created with an initial contents value of 0.

When the on idle handler triggers, the run count default entry is retrieved from the user defaults, incremented, and displayed in a dialog. The incremented run count is then applied back to the appropriate default entry in the user defaults. When the application quits, this information is stored in the property list file for the application. Therefore, if this application is triggered multiple times, the run count value will continue to increment with each new execution.

User defaults provide yet another way to store and access data during script execution, though only in AppleScript Studio projects.

Other Options

I would like to also take a moment to mention that there are other ways that you may choose to store and retrieve data, should you decide that the methods mentioned previously do not meet your needs in a particular situation. One way is to store data in a standard text file of some type. Typically, a delimited format of some type makes a good choice, although it may require that you write some fancy parsing code. Another choice could be to store your data in a database, such as FileMaker Pro. If you're using Mac OS X 10.4 or higher, then you could also consider exploring Database Events further, which was the topic of last month's column.

In Closing

Hopefully, I have been able to provide some insight into several possible methods of data storage. Obviously, you are certainly not bound to make use of only the techniques that I discussed. There are other mechanisms, which I encourage you to explore. However, the techniques that I have mentioned are the most commonly used among scripters, and generally do provide you with a variety of relatively quick and easy ways to store and retrieve data using AppleScript.

Until next time, keep scripting!


Ben Waldie is author of the best selling books "AppleScripting the Finder" and the "Mac OS X Technology Guide to Automator", available from http://www.spiderworks.com. Ben is also president of Automated Workflows, LLC, a firm specializing in AppleScript and workflow automation consulting. For years, Ben has developed professional AppleScript-based solutions for businesses including Adobe, Apple, NASA, PC World, and TV Guide. For more information about Ben, please visit http://www.automatedworkflows.com, or email Ben at applescriptguru@mac.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.