Xcode:读取plist数据并将其显示为文本

时间:2016-08-03 16:25:35

标签: xcode applescript appdelegate

我完全忘记了Xcode AppleScript Application。

基本上,应用程序将从plist文件中读取值。

我的AppleScript读取此变量是

set the plistfile_path to "~/Desktop/example.plist"

tell application "System Events"
    set p_list to property list file (plistfile_path)
    -- read the plist data
    set theNameFromPlist to value of property list item "theName" of p_list
    set theEmailFromPlist to value of property list item "theEmail" of p_list
    set thecreationDateFromPlist to value of property list item "creationDate" of p_list


end tell

现在如何将其集成到Xcode中?

我应该继续使用AppDelegate.applescript并在“applicationWillFinishLaunching_(aNotification)”之后的任何地方添加此脚本吗?

followed by  property NametextField : theNameFromPlist

我在这里可能完全错了,只是想不到。 如果更容易,PS swift将会这样做

2 个答案:

答案 0 :(得分:1)

就像vadian在评论中所说的那样,在Xcode中,系统事件不能正常运行所以你可以只使用本机Cocoa类但我更喜欢 使用"做shell脚本" applescript / asobjc命令并运行"默认值"命令所以这是一种在应用程序完成启动时执行此操作的方法:

on applicationWillFinishLaunching_(aNotification)
    set plistFile to "~/Desktop/example.plist"
    set theNameFromPlist to do shell script "defaults read " & plistFile & " theName"
    set theEmailFromPlist to do shell script "defaults read " & plistFile & " theEmail"
    set theCreationDateFromPlist to do shell script "defaults read " & plistFile & " creationDate"
end applicationWillFinishLaunching_

如果您尝试在窗口的TextField中显示名称 在Interface Builder中,您只需添加修改代码即可:

property nameTextField : missing value

on applicationWillFinishLaunching_(aNotification)
    set plistFile to "~/Desktop/example.plist"
    set theNameFromPlist to do shell script "defaults read " & plistFile & " theName"
    set theEmailFromPlist to do shell script "defaults read " & plistFile & " theEmail"
    set theCreationDateFromPlist to do shell script "defaults read " & plistFile & " creationDate"
    tell nameTextField to setStringValue_(theNameFromPlist)
end applicationWillFinishLaunching_

(确保将属性nameTextField连接到Interface Builder中的TextField)

希望这有助于!! :d

答案 1 :(得分:1)

提到Cocoa类我实际上是指这个

set plistFile to POSIX path of (path to desktop) & "example.plist"
set thePlist to (current application's NSDictionary's dictionaryWithContentsOfFile:plistFile) as record
set theNameFromPlist to thePlist's theName
set theEmailFromPlist to thePlist's theEmail

要添加新的键值对并将plist写回磁盘,请添加

set thePlist to thePlist & {stringKey:"Foo", booleanKey:false}
set cocoaDictionary to current application's NSDictionary's dictionaryWithDictionary:thePlist
cocoaDictionary's writeToFile:plistFile atomically:true