Read and write property lists

In the past, I’ve used properties and later text files to save persistent values. I’m rewriting many of my scripts to use ASObjC and decided to switch to property lists. My needs in this regard are simple–read a string or list from the property list at the beginning of the script and write a new string or list at the end. I’ve included the handlers I use for this purpose below.

A few comments:

  • For brevity of code, I included both read and write functions in one handler but they could easily be separated.

  • Both the value “com.peavine.TestScriptName” and the default read value should be changed to whatever is applicable for the script.

  • In his book, Shane discusses two approaches that can be used to accomplish what I want. I used the one which did not require explicit bridging of a list to an array.

  • I’m new to ASObjC and would welcome any suggestions to make the handlers better.

The string handler:

use framework "Foundation"
use scripting additions

set theString to "Test String"
readOrWritePlist("write", theString) -- write property list
readOrWritePlist("read", "") -- read property list

on readOrWritePlist(readOrWrite, theString)
	set theDefaults to current application's NSUserDefaults's alloc()'s initWithSuiteName:"com.peavine.TestScriptName"
	if readOrWrite = "read" then
		theDefaults's registerDefaults:{theKey:"Default String"}
		set theString to theKey of theDefaults as text
		return theString
	else
		set theKey of theDefaults to theString
	end if
end readOrWritePlist

The list handler:

use framework "Foundation"
use scripting additions

set theList to {"String One", "String Two"}
readOrWritePlist("write", theList) -- write property list
readOrWritePlist("read", "") -- read property list

on readOrWritePlist(readOrWrite, theList)
	set theDefaults to current application's NSUserDefaults's alloc()'s initWithSuiteName:"com.peavine.TestScriptName"
	if readOrWrite = "read" then
		theDefaults's registerDefaults:{theKey:{"Default String One", "Default String Two"}}
		set theList to theKey of theDefaults as list
		return theList
	else
		set theKey of theDefaults to theList
	end if
end readOrWritePlist

One desirable feature of the above approach is that it’s very flexible as to class of the item stored. The following is from Shane’s book:

Edit March 14, 2021

In retrospect, my suggestion was not a very good one. I’ll leave it just FWIW.

It’s probably worth your downloading my PrefStorageLib from https://latenightsw.com/support/freeware, if only to look at the code. It represents some of my thinking about the issue since I wrote the book.

In retrospect, my scripts in post 1 are not well written and should not be used. I’ll leave this thread in place so that interested forum members will be able to view Shane’s good advice.