AppleScriptObj-C Routines
AppleScriptObjective-C (also called: AppleScriptObj-C or ASOC) is the dynamic fusion of the AppleScript and Objective-C languages, providing access within scripts to the classes and methods of the core Cocoa frameworks of macOS, while also possessing the ability to query and command applications throughout macOS via Apple Events.
For its 20th anniversary debut in OS X Mavericks, AppleScript gained a long-sought ability: an import command — dramatically extending the scope and power of this unique language.
A new AppleScript construct called the “use statement” imports the terminology and functionality of AppleScript Libraries and scriptable Applications through a simple single-line declaration placed at the top of a script, such as:
The handlers, scriptable objects, properties, and terminology of AppleScript Libraries and scriptable applications imported via a “use statement,” are automatically available globally throughout the hosting script, no longer requiring numerous “tell statements” or “tell blocks” to be compiled and executed. Scripts taking advantage of the “use statement” are more streamlined and clearer than similar scripts not implementing this new construct.
In addition, AppleScript Libraries written in AppleScript/Objective-C, can incorporate “use” statements to import Cocoa frameworks, such as MapKit, EventKit, and WebKit.
AppleScript/Objective-C is available to all scripts, not just library scripts. To use an Objective-C framework in your script, you must specify it with a use statement, such as: use framework "Foundation"
| Use Statements | ||
| 01 | use AppleScript version "2.4" | |
| 02 | use framework "Foundation" | |
| 03 | use scripting additions | |
Here’s a short video demonstrating the use of AppleScriptObj-C to sort a list on names:
Important AppleScriptObj-C Constructs
Here are rules to follow when writing AppleScriptObj-C.
1) Identify Cocoa classes and enumerations as belonging to the current application.
| Cocoa Class | ||
| 01 | current application's ClassName | |
| Enumeration | ||
| 01 | set anEnumeration to current application's enumerationName | |
| 02 | current application's ClassName's methodName:anEnumeration | |
2) Cocoa methods are separated from their parameter values by colons, and are shown to belong to their parent class.
| Objective-C Methods | ||
| 01 | set aResult to ¬ | |
| 02 | current application's ClassName's methodName:aValue parameter:aValue | |
3) When retrieving the value of a Cocoa property, the property name is written ending with open/close parens ()
| Retrieving Property Values | ||
| 01 | set aValue to CocoaObject's propertyName() | |
4) When setting the value of a Cocoa Object's property, no ending parens are included. Optionally the property may be used as a method by placing the term set before its capitalized version, followed by a colon and the new value.
| Setting Value of Cocoa Object's Property | ||
| 01 | set CocoaObject's propertyName to aValue | |
| 02 | ||
| 03 | CocoaObject's setPropertyName:aValue | |
Hre are some supporting reference links:
EverdayAppleScriptObjC by Shane Stanely
Mac Automation Scripting Guide
Strings
AppleScriptObj-C provides access to the NSString class of the Foundation frameworks, containing methods for easily manipulating text strings, even those used as paths representing the location of disk items.
The following routines use methods and properties of the NSString class to simplify common text manipulations that are more difficult to perform using the AppleScript language alone.
Converting to Objective-C and Back
There is a typical process for manipulating AppleScript text strings using the NSString class methods and properties of the Frameworks framework. AppleScript text strings are first converted to Objective-C text objects, manipulated using Cocoa class methods and properties, and the result is then coerced back into an AppleScript text string.
| NSString's stringWithString Method | ||
| 01 | set cocoaString to ¬ | |
| 02 | current application's NSString's stringWithString:"Happy Birthday" | |
| 03 | ||
| 04 | -- do something with the cocoa string | |
| 05 | ||
| 06 | -- return the result coerced to an AppleScript string | |
| 07 | return (cocoaString as text) | |
01-02 In order to process the provided text, it must be first converted into an Objective-C text object using the stringWithString method.
07 After manipulating the Objective-C text object, the final text object is returned as an AppleScript text string by using the “as text” coercion.
The following examples use the described procedure to perform common text manipulations.
Change Case
The native AppleScript language does not offer built-in methods for converting the case of text strings. AppleScriptObj-C can be used to access the NSString methods and properties to change the case of text.
| Change Case | ||
| 01 | on changeCaseOfText(sourceText, caseIndicator) | |
| 02 | set the sourceString to ¬ | |
| 03 | current application's NSString's stringWithString:sourceText | |
| 04 | -- apply the indicated transformation to the Cocoa string | |
| 05 | if the caseIndicator is 0 then | |
| 06 | -- optional: localizedUppercaseString | |
| 07 | set the adjustedString to sourceString's uppercaseString() | |
| 08 | else if the caseIndicator is 1 then | |
| 09 | -- optional: localizedLowercaseString | |
| 10 | set the adjustedString to sourceString's lowercaseString() | |
| 11 | else | |
| 12 | -- optional: localizedCapitalizedString | |
| 13 | set the adjustedString to sourceString's capitalizedString() | |
| 14 | end if | |
| 15 | -- convert from Cocoa string to AppleScript string | |
| 16 | return (adjustedString as text) | |
| 17 | end changeCaseOfText | |
Trim Whitespace
Here a routine for removing tabs, spaces, and paragraph returns from the beginning and end of a provided text string. Use the whitespaceCharacterSet property to remove only tabs and spaces, but not line feeds and returns.
| Trim Whitespace Around String | ||
| 01 | on trimWhiteSpaceAroundString(thisString) | |
| 02 | set cocoaString to ¬ | |
| 03 | current application's NSString's stringWithString:thisString | |
| 04 | set whiteSpaceCharacters to ¬ | |
| 05 | current application's NSCharacterSet's whitespaceAndNewlineCharacterSet() | |
| 06 | set cocoaString to cocoaString's stringByTrimmingCharactersInSet:whiteSpaceCharacters | |
| 07 | return (cocoaString as text) | |
| 08 | end trimWhiteSpaceAroundString | |
Replace Text in String
Here’s a routine for finding and replacing a text string from within larger strings.
| Replace String in String | ||
| 01 | on replaceStringInString(sourceText, searchString, replacementString) | |
| 02 | set aString to current application's NSString's stringWithString:sourceText | |
| 03 | set resultString to ¬ | |
| 04 | aString's stringByReplacingOccurrencesOfString:searchString withString:replacementString | |
| 05 | return resultString as text | |
| 06 | end replaceStringInString | |
Base Name of a File
The NSString class contains methods and properties that are designed to manipulate POSIX file paths that indicated the location of disk items.
In the following example, the base name (file name without file extension) is returned from a passed file reference.
| Base Name of a File | ||
| 01 | on basenameFromFileReference(aReference) | |
| 02 | -- get the POSIX path of the file reference | |
| 03 | set aPath to the POSIX path of aReference | |
| 04 | -- convert to a Cocoa string | |
| 05 | set cocoaString to ¬ | |
| 06 | current application's NSString's stringWithString:aPath | |
| 07 | -- get the last path item | |
| 08 | set fileName to cocoaString's lastPathComponent() | |
| 09 | -- remove the file extension | |
| 10 | set baseName to fileName's stringByDeletingPathExtension() | |
| 11 | -- return as AppleScript string | |
| 12 | return baseName as text | |
| 13 | end basenameFromFileReference | |
Container of a File
The NSString class contains methods and properties that are designed to manipulate POSIX file paths that indicated the location of disk items.
In the following example, an alias reference to the containing folder of a passed file reference is returned.
| Container of File | ||
| 01 | on containingFolderFromFileReference(aReference) | |
| 02 | -- get the POSIX path of the file reference | |
| 03 | set aPath to the POSIX path of aReference | |
| 04 | -- convert to a Cocoa string | |
| 05 | set cocoaString to ¬ | |
| 06 | current application's NSString's stringWithString:aPath | |
| 06 | -- remove the last path item | |
| 07 | set parentPath to cocoaString's stringByDeletingLastPathComponent() | |
| 08 | -- append closing slash and convert POSIX path to alias | |
| 09 | return ((parentPath as text) & "/") as POSIX file as alias | |
| 10 | end containingFolderFromFileReference | |
POSIX Path of Item
This routine will return a POSIX path for the designated file reference. Accepts: aliases, file URLs, POSIX files, and relative paths
| POSIX Path from Item Reference | ||
| 01 | on returnPOSIXPathForItem(itemReference) | |
| 02 | (* This routine attempts to return a clean full POSIX path reference *) | |
| 03 | -- check class of input | |
| 04 | if the class of itemReference is alias then | |
| 05 | set itemReference to the POSIX path of itemReference | |
| 06 | else if the class of itemReference is «class furl» then | |
| 07 | set itemReference to the POSIX path of itemReference | |
| 08 | else if class of itemReference is string then | |
| 09 | if itemReference begins with "'" and ¬ | |
| 10 | itemReference ends with "'" then | |
| 11 | -- remove single quotes | |
| 12 | set itemReference to text 2 thru -2 of itemReference | |
| 13 | end if | |
| 14 | if itemReference begins with "~" then | |
| 15 | set CocoaString to ¬ | |
| 16 | current application's NSString's stringWithString:itemReference | |
| 17 | set itemReference to ¬ | |
| 18 | (CocoaString's stringByExpandingTildeInPath()) as text | |
| 19 | end if | |
| 20 | set itemReference to POSIX path of itemReference | |
| 21 | end if | |
| 22 | return itemReference | |
| 23 | end returnPOSIXPathForItem | |
Derive Path for File in Specified Folder
This routine is very useful when you are creating new files in a specific folder. The routine will check to see if a file with the provided name already exists, and if it does, generate a unique numerically incremented version. For example, if the file named "Report.txt" is already in the target folder, the routine will return a path for the new file with the incremented name "Report-1.txt"
| Derive Path for New File in Specified Folder | ||
| 01 | on derivePathForNewFileInSpecifiedFolder(targetDirectory, documentTitleToUse, documentExtensionToUse) | |
| 02 | set targetFolderPath to the POSIX path of targetDirectory | |
| 03 | if targetFolderPath does not end with "/" then set targetFolderPath to targetFolderPath & "/" | |
| 04 | set documentBaseNamePath to targetFolderPath & documentTitleToUse | |
| 05 | set documentFullPath to documentBaseNamePath & "." & documentExtensionToUse | |
| 06 | set aFileManager to current application's NSFileManager's defaultManager() | |
| 07 | set incrementIndex to 0 | |
| 08 | repeat while (aFileManager's fileExistsAtPath:documentFullPath) | |
| 09 | set incrementIndex to incrementIndex + 1 | |
| 10 | set documentFullPath to ¬ | |
| 11 | documentBaseNamePath & "-" & incrementIndex & "." & documentExtensionToUse | |
| 12 | end repeat | |
| 13 | return documentFullPath | |
| 14 | end derivePathForNewFileInSpecifiedFolder | |
Number to Formatted Currency String
This routine will convert the passed number into a formatted currency string using the current locale.
| Number to Formatted Currency String | ||
| 01 | on convertNumberToCurrencyValueString(thisNumber) | |
| 02 | --> returns comma delimited, rounded, localized currency value | |
| 03 | --> e.g.: (9128 = $9,128.00) (9978.2485 = $9,128.25) | |
| 04 | set currencyStyle to current application's NSNumberFormatterCurrencyStyle | |
| 05 | set resultingText to ¬ | |
| 06 | current application's NSNumberFormatter's localizedStringFromNumber:thisNumber numberStyle:currencyStyle | |
| 07 | return (resultingText as text) | |
| 08 | end convertNumberToCurrencyValueString | |
Number to Percentage Value String
This routine will convert a decimal value into a percentage value string.
| Number to Percentage Value String | ||
| 01 | on convertNumberToPercentageValueString(thisNumber) | |
| 02 | --> returns comma delimited, rounded, localized percentage value, e.g.: (0.2345 = 23%) (0.2375 = 24%) | |
| 03 | set percentstyle to ¬ | |
| 04 | current application's NSNumberFormatterPercentStyle | |
| 05 | set resultingText to ¬ | |
| 06 | current application's NSNumberFormatter's localizedStringFromNumber:thisNumber numberStyle:percentstyle | |
| 07 | return (resultingText as text) | |
| 08 | end convertNumberToPercentageValueString | |
Number to Words
This routine converts the passed number into a phrase. For example, 12345678 becomes twelve million three hundred forty-five thousand six hundred seventy-eight.
| Number to Words | ||
| 01 | on convertNumberToWords(thisNumber) | |
| 02 | --> returns a numeric value in words, e.g: (23 = “twenty-three”) (23.75 = “twenty-three point seven five”) | |
| 03 | set numberStyle to current application's NSNumberFormatterSpellOutStyle | |
| 04 | set resultingText to ¬ | |
| 05 | current application's NSNumberFormatter's localizedStringFromNumber:thisNumber numberStyle:numberStyle | |
| 06 | return (resultingText as text) | |
| 07 | end convertNumberToWords | |
Number to Decimal String
This routine will return a decimal string from the provided numeric value. You can indicate a specific decimal length for the resulting value. In addition, the numeric value will automatically be rounded during the process of adding decimals.
| Number to Decimal String | ||
| 01 | on convertNumberToDecimalString(theNumber, theNumberOfDecimalPlaces) | |
| 02 | set theFormatter to current application's NSNumberFormatter's new() | |
| 03 | set theFormatter's minimumFractionDigits to theNumberOfDecimalPlaces | |
| 04 | set theFormatter's maximumFractionDigits to theNumberOfDecimalPlaces | |
| 05 | set theFormattedNumber to theFormatter's stringFromNumber:theNumber | |
| 06 | return (theFormattedNumber as text) | |
| 07 | end convertNumberToDecimalString | |
Number to Ordinal String
Creates an ordinal string based upon the provided number. For example, 23 derives 23rd.
| Number to Ordinal String | ||
| 01 | on numberToOrdinalString(thisNumber) | |
| 02 | set theFormatter to current application's NSNumberFormatter's new() | |
| 03 | set thisNumberStyle to ¬ | |
| 04 | current application's NSNumberFormatterOrdinalStyle | |
| 05 | tell theFormatter to set its numberStyle to thisNumberStyle | |
| 06 | return (theFormatter's stringFromNumber:thisNumber) as text | |
| 07 | end numberToOrdinalString | |
Number to String
This routine converts the passed number to a string. Especially useful for converting scientific notation to “normal” numbers. For example, 1.23456789E+9 becomes 1234567890.
| Number to String | ||
| 01 | on numberToString(thisNumber) | |
| 02 | set theFormatter to current application's NSNumberFormatter's new() | |
| 03 | set thisNumberStyle to current application's NSNumberFormatterNoStyle | |
| 04 | tell theFormatter to set its numberStyle to thisNumberStyle | |
| 05 | return (theFormatter's stringFromNumber:thisNumber) as text | |
| 06 | end numberToString | |
List from String
This routine divides a string into a list of components based upon the indicated delimiter.
| Break String into Components | ||
| 01 | on getItemsFromDelimitedString(thisString, thisDelimiter) | |
| 02 | set thisString to ¬ | |
| 03 | current application's NSString's stringWithString:thisString | |
| 04 | set theseStrings to ¬ | |
| 05 | thisString's componentsSeparatedByString:thisDelimiter | |
| 06 | return theseStrings as list | |
| 07 | end getItemsFromDelimitedString | |
List to String
This routine combines the elements of a list into a delimited string.
| List to String | ||
| 01 | on stringFromList(thisList, thisDelimiterString) | |
| 02 | -- convert from AppleScript list to Cocoa array | |
| 03 | set thisArray to ¬ | |
| 04 | current application's NSArray's arrayWithArray:thisList | |
| 05 | -- create Cocoa string from array | |
| 06 | set combinedItemsString to ¬ | |
| 07 | thisArray's componentsJoinedByString:thisDelimiterString | |
| 08 | -- return result as AppleScript string | |
| 09 | return combinedItemsString as text | |
| 10 | end stringFromList | |
Percent Encode the String
This routine will percent encode all non-alphanumeric characters in a string. For example, a space will replaced with %20.
| Percent Encode String | ||
| 01 | on encodeUsingPercentEncoding(sourceText) | |
| 02 | -- create a Cocoa string from the passed AppleScript string | |
| 03 | set sourceString to ¬ | |
| 04 | current application's NSString's stringWithString:sourceText | |
| 05 | -- indicate the allowed characters that do not get encoded | |
| 06 | set allowedCharacterSet to ¬ | |
| 07 | current application's NSCharacterSet's alphanumericCharacterSet | |
| 08 | -- apply the indicated transformation to the Cooca string | |
| 09 | set adjustedString to ¬ | |
| 10 | sourceString's stringByAddingPercentEncodingWithAllowedCharacters: | |
| 11 | -- convert from Cocoa string to AppleScript string | |
| 12 | return (adjustedString as text) | |
| 13 | end encodeUsingPercentEncoding | |
Decode Percent Encoded String
This routine will replace percent encoding in a string with corresponding characters.
| Decode Percent Encoded String | ||
| 01 | on decodePercentEncoding(sourceText) | |
| 02 | -- create a Cocoa string from the passed AppleScript string | |
| 03 | set sourceString to ¬ | |
| 04 | current application's NSString's stringWithString:sourceString | |
| 05 | -- apply the indicated transformation to the Cooca string | |
| 06 | set adjustedString to ¬ | |
| 07 | sourceString's stringByRemovingPercentEncoding() | |
| 08 | -- coerce from Cocoa string to AppleScript string | |
| 09 | return (adjustedString as text) | |
| 10 | end decodePercentEncoding | |
Arrays
Here are series of routines for manipulating lists (arrays).
Sort List
Here’s a routine for alphabetically sorting a list.
| Sort List | ||
| 01 | on sortListOfStrings(theList) | |
| 02 | -- convert list to Cocoa array | |
| 03 | set theArray to ¬ | |
| 04 | current application's NSArray's arrayWithArray:theList | |
| 05 | -- sort the array using a specific function | |
| 06 | set theArray to ¬ | |
| 07 | theArray's sortedArrayUsingSelector:"localizedStandardCompare:" | |
| 08 | -- return the sorted array as an AppleScript list | |
| 09 | return theArray as list | |
| 10 | end sortListOfStrings | |
Insert Item in List
This routine inserts an item in the provided list at the indicated position. The first position is 1 not 0.
| Insert Item in List | ||
| 01 | on insertItemInList(anItem, theIndex, theList) | |
| 02 | -- create an editable array from the list | |
| 03 | set theArray to ¬ | |
| 04 | current application's NSMutableArray's arrayWithArray:theList | |
| 05 | -- insert item at position. Index of first postion is 1 not 0 | |
| 06 | theArray's insertObject:anItem atIndex:(theIndex - 1) | |
| 07 | -- return Cocoa array as an AppleScript list | |
| 08 | return theArray as list | |
| 09 | end insertItemInList | |
Remove Item from List
This routine removes all occurrences of an indicated item from the provided list.
| Remove Item from List | ||
| 01 | on deleteOccurencesOfItemFromList(anItem, theList) | |
| 02 | -- create an editable Cocoa array | |
| 03 | set theArray to ¬ | |
| 04 | current application's NSMutableArray's arrayWithArray:theList | |
| 05 | -- remove the item from the array | |
| 06 | theArray's removeObject:anItem | |
| 07 | -- return the array as an AppleScript list | |
| 08 | return theArray as list | |
| 09 | end deleteOccurencesOfItemFromList | |
Index of First Occurence in List
This routine returns the index of the first occurence of an item in a list. If item is not in the list, then 0 is returned.
| Index of First Occurence in List | ||
| 01 | on indexOfItemInList(aValue, theList) | |
| 02 | -- convert list to Cocoa array | |
| 03 | set theArray to ¬ | |
| 04 | current application's NSArray's arrayWithArray:theList | |
| 05 | -- get the index of the first occurence of the item | |
| 06 | set theIndex to (theArray's indexOfObject:aValue) | |
| 07 | -- check the class of the result | |
| 08 | if class of theIndex is real then | |
| 09 | return 0 | |
| 10 | else | |
| 11 | -- return the index adjusted for AppleScript | |
| 12 | return (theIndex + 1) | |
| 13 | end if | |
| 14 | end indexOfItemInList | |
Remove Items at Indexes
This routine will remove the items at the provided indexes.
| Delete List Items at Indexes | ||
| 01 | on deleteListItemsAtIndexes(theIndexes, theList) | |
| 02 | -- create an editable array | |
| 03 | set theArray to ¬ | |
| 04 | current application's NSMutableArray's arrayWithArray:theList | |
| 05 | -- create an empty index set | |
| 06 | set theSet to ¬ | |
| 07 | current application's NSMutableIndexSet's indexSet() | |
| 08 | -- add the index matches to the set | |
| 09 | repeat with anIndex in theIndexes | |
| 10 | (theSet's addIndex:(anIndex - 1)) | |
| 11 | end repeat | |
| 12 | -- remove matched items | |
| 13 | theArray's removeObjectsAtIndexes:theSet | |
| 14 | -- return the edited array as list | |
| 15 | return theArray as list | |
| 16 | end deleteListItemsAtIndexes | |
Records
Routines for manipulating records.
New Record from Lists
Turn a list of keys and a list of corresponding values into an AppleScript record.
| Convert Lists to Record | ||
| 01 | on recordFromLabelsAndValues(theseLabels, theseValues) | |
| 02 | -- create a Cocoa dictionary using lists of keys and values | |
| 03 | set theResult to ¬ | |
| 04 | current application's NSDictionary's dictionaryWithObjects:theseValues forKeys:theseLabels | |
| 05 | -- return the resulting dictionary as an AppleScript record | |
| 06 | return theResult as record | |
| 07 | end recordFromLabelsAndValues | |
Property Lists
Routines for manipulating standard property lists (plist).
Here is a simple sample property list file (DOWNLOAD) containing a single key/value pair.
| Example Property List | ||
| 01 | <?xml version="1.0" encoding="UTF-8"?> | |
| 02 | <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> | |
| 03 | <plist version="1.0"> | |
| 04 | <dict> | |
| 05 | <key>City</key> | |
| 06 | <string>San Francisco</string> | |
| 07 | </dict> | |
| 08 | </plist></div> | |
Edit Value of Existing Key
Here is an example script showing how to edit the value of the specified key in the property list. NOTE: the sub-routine in this example is written in Cocoa format with the values for the function and parameters following colon (":") characters:
| Change Value for Property List Key | ||
| 01 | use framework "Foundation" | |
| 02 | use scripting additions | |
| 03 | ||
| 04 | -- READ THE CONTENTS AN EXISTING PROPERTY LIST INTO EDITABLE DICTIONARY | |
| 05 | set pListFilePath to "~/Desktop/Sample.plist" | |
| 06 | set pListFilePath to ¬ | |
| 07 | current application's NSString's stringWithString:pListFilePath | |
| 08 | set pListFilePath to pListFilePath's stringByExpandingTildeInPath() | |
| 09 | set sourceDictionary to ¬ | |
| 10 | current application's NSMutableDictionary's dictionaryWithContentsOfFile:pListFilePath | |
| 11 | -- EDIT THE VALUE OF AN EXISTING KEY/VALUE PAIR | |
| 12 | sourceDictionary's setObject:"Seattle" forKey:"City" | |
| 13 | -- WRITE EDITED DICTIONARY BACK TO PROPERTY LIST | |
| 14 | its storeRecord:sourceDictionary inPath:pListFilePath | |
| 15 | ||
| 16 | -- THE SUB-ROUTINE IN COCOA FORMAT | |
| 17 | on storeRecord:theRecord inPath:thePath | |
| 18 | set thePath to ¬ | |
| 19 | current application's NSString's stringWithString:thePath | |
| 20 | set thePath to ¬ | |
| 21 | thePath's stringByExpandingTildeInPath() | |
| 22 | set savingFormat to current application's NSPropertyListBinaryFormat_v1_0 | |
| 23 | set theData to ¬ | |
| 24 | current application's NSPropertyListSerialization's dataWithPropertyList:theRecord format:savingFormat options:0 |error|:(missing value) | |
| 25 | theData's writeToFile:thePath atomically:true | |
| 26 | log result -- so we can see if it saved | |
| 27 | end storeRecord:inPath: | |
FYI: here’s a basic routine for retrieving the value of a property list element:
| Retrieve the Value of a Property List Element | ||
| 01 | use framework "Foundation" | |
| 02 | use scripting additions | |
| 03 | ||
| 04 | -- DERIVE A COMPLETE POSIX PATH TO PROPERTY LIST | |
| 05 | set pListFilePath to "~/Desktop/Sample.plist" | |
| 06 | set pListFilePath to ¬ | |
| 07 | current application's NSString's stringWithString:pListFilePath | |
| 08 | set pListFilePath to ¬ | |
| 09 | pListFilePath's stringByExpandingTildeInPath() | |
| 10 | set pListURL to ¬ | |
| 11 | current application's NSURL's fileURLWithPath:pListFilePath isDirectory:false | |
| 12 | -- READ THE PROPERTY LIST INTO MEMORY | |
| 13 | set sourceDictionary to ¬ | |
| 14 | current application's NSDictionary's dictionaryWithContentsOfURL:pListURL |error|:(missing value) | |
| 15 | -- GET VALUE FOR ELEMENT | |
| 16 | set aValue to (sourceDictionary's objectForKey:"City") as text | |
Here’s an example of creating a property list containing multiple elements, each of which is an array:
The resulting property list:
| Multi-Element Property List | ||
| 01 | <?xml version="1.0" encoding="UTF-8"?> | |
| 02 | <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> | |
| 03 | <plist version="1.0"> | |
| 04 | <dict> | |
| 05 | <key>firstElement</key> | |
| 06 | <array> | |
| 07 | <integer>1</integer> | |
| 08 | <integer>3</integer> | |
| 09 | <integer>4</integer> | |
| 10 | <integer>7</integer> | |
| 11 | <integer>9</integer> | |
| 12 | </array> | |
| 13 | <key>secondElement</key> | |
| 14 | <array> | |
| 15 | <string>Monday</string> | |
| 16 | <string>Tuesday</string> | |
| 17 | <string>Wednesday</string> | |
| 18 | <string>Thursday</string> | |
| 19 | <string>Friday</string> | |
| 20 | <string>Saturday</string> | |
| 21 | <string>Sunday</string> | |
| 22 | </array> | |
| 23 | </dict> | |
| 24 | </plist> | |
Bookmarks
Routine for generating a minimal bookmark to a file. This routine returns bookmark data that can later be resolved into a URL object for a file even if the user moves or renames it (if the volume format on which the file resides supports doing so).
| Generate Minimal Bookmark Data for File | ||
| 01 | use AppleScript version "2.4" -- Yosemite (10.10) or later | |
| 02 | use framework "Foundation" | |
| 03 | use scripting additions | |
| 04 | ||
| 05 | set aPath to (choose file) | |
| 06 | its getBookmarkDataFor:aPath | |
| 07 | ||
| 08 | on getBookmarkDataFor:aPath | |
| 09 | if class of aPath is not string then | |
| 10 | set aPath to the POSIX path of aPath | |
| 11 | else | |
| 12 | set aPath to current application's NSString's stringWithString:aPath | |
| 13 | set aPath to aPath's stringByExpandingTildeInPath() | |
| 14 | end if | |
| 15 | set theURL to current application's NSURL's fileURLWithPath:aPath | |
| 16 | set bookmarkData to ¬ | |
| 17 | theURL's bookmarkDataWithOptions:0 includingResourceValuesForKeys:{} relativeToURL:(missing value) |error|:(missing value) | |
| 18 | return bookmarkData | |
| 19 | end getBookmarkDataFor | |
This webpage is in the process of being developed. Any content may change and may not be accurate or complete at this time.