【问题标题】:Global preferences for AppleScript appAppleScript 应用程序的全局首选项
【发布时间】:2011-05-05 18:03:52
【问题描述】:

是否可以为在 AppleScript 中创建的应用保存某种设置?

设置应在脚本开头加载并在脚本末尾保存。

例子:

if loadSetting("timesRun") then
    set timesRun to loadSetting("timesRun")
else
    set timesRun to 0
end if
set timesRun to timesRun + 1
display dialog timesRun
saveSetting("timesRun", timesRun)

第一次运行脚本时对话框将显示 1,第二次运行时显示 2...

而函数 loadSetting 和 saveSetting 将是我需要的函数。

【问题讨论】:

    标签: applescript


    【解决方案1】:

    脚本properties 是持久的,但无论何时重新保存脚本,保存的值都会被脚本中指定的值覆盖。运行:

    property |count| : 0
    display alert "Count is " & |count|
    set |count| to |count| + 1
    

    几次,重新保存然后再运行几次。

    如果您想使用用户默认系统,您可以使用do shell script "defaults ..." 命令或(如果使用 Applescript Studio)default entry "propertyName" of user defaults。在 Applescript Studio 中,你 bind values to user defaults

    【讨论】:

      【解决方案2】:

      这也很好用(检查提示的第一条评论):

      http://hints.macworld.com/article.php?story=20050402194557539

      它使用“默认”系统,您可以在 ~/Library/Preferences 中获得您的偏好

      【讨论】:

        【解决方案3】:

        Applescript 通过系统事件支持原生读写 plist:

        use application "System Events" # Avoids tell blocks, note: 10.9 only
        
        property _myPlist : "~/Library/Preferences/com.plistname.plist
        
        set plistItemValue to get value of property list item "plistItem" of contents of property list file _myPlist
        set plistItemValue to plistItemValue + 1
        
        set value of property list item "plistItem" of contents of property list file _myPlist to plistItemValue
        

        唯一的问题是它无法创建 plist,因此如果不确定 plist 的存在,您需要将其包装在 try 上。

        try 
            set plistItemValue to get value of property list item "plistItem" of contents of property list file _myPlist
        on error -1728 # file not found error
            do shell script "defaults write com.plistname.plist plistItem 0"
            set plistItemValue to get value of property list item "plistItem" of contents of property list file _myPlist
        end try
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-02-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-08
          • 2017-04-21
          相关资源
          最近更新 更多