Question about storing a retrieving information...


I have an application that stores the users preferences in a plist inside of the application bundle; it uses defaults to read and write. I’m currently trying to get it to do a few things, pretty simple, though.

The first is to read the defaults at startup, then set the corresponding UI element to that value.

set remoteLogin to (do shell script "defaults read " & quoted form of ((the POSIX path of (path to me) & "Contents/Resources/") & "com.visuals.setup") & " remoteLogin" as boolean)
set state of button "remoteLogin" to remoteLogin

The second is to read the UI element’s value, and store it as a variable to be cross checked with what that value should be.

set remoteLogin to (state of button "remoteLogin") as boolean

The third is to take that variable and write it to defaults to be read at the next launch or while being executed.

do shell script ("defaults write " & quoted form of ((the POSIX path of (path to me) & "Contents/Resources/") & "com.visuals.setup ") & " remoteLogin '" & remoteLogin & "'")

These are all done in the order given above.

It currently doesn’t seem to be working. I have it logging the value at each step and it seems to be correct until it reads from defaults, it returns with the incorrect value, even if I open the plist and it contains the correct value.

Any idea what I’m missing, what’s wrong with my code?

Any suggestions for improvement?


One more thing…

I’d like to do the same with a date picker, but I can’t seem to set values at all.

Any ideas?


if no type is specified while writing a value, /usr/bin/defaults writes the value as type text,
therefore I recommend to write the value as a specified type (e.g. -bool in your example).
While reading the value you have to coerce it to the appropriate type

Here an example:

property setupPlist : missing value

set setupPlist to POSIX path of (path to me) & "Contents/Resources/com.visuals.setup"

set remoteLogin to true
writeDefaults(setupPlist, "remoteLogin", "-bool", remoteLogin as text)
set remoteLogin to missing value
set remoteLogin to readDefaults(setupPlist, "remoteLogin") as integer as boolean
remoteLogin --> true

on readDefaults(_domain, _key)
	return (do shell script "/usr/bin/defaults read " & quoted form of _domain & space & _key)
end readDefaults

on writeDefaults(_domain, _key, _type, _value)
	return (do shell script "/usr/bin/defaults write " & quoted form of _domain & space & _key & space & _type & space & _value)
end writeDefaults

For the date picker you can coerce the date to text and save it

Thanks Stefan, that is some great info; I really appreciate it!

What I was wondering about the Date Picker was how to write the values back to the Date Picker UI element.

set contents of control "startTime" to startTime

Is what I have but it doesn’t seem to work!