Applescript Get value of property by string name of property

眉间皱痕 提交于 2019-12-13 08:18:54

问题


In AppleScript. Let's say I have a record with a property called Title.

Let's say I set a variable to the text "Title"; can I use that variable to get the value of the property Title? Basically, is there any way to do something like this:

set result to property named "Title" of myRecord

Instead of:

set result to Title of myRecord

回答1:


I found the answer. I also realize I didn't ask the correct question. The value I'm trying to obtain is from a property list item.

Here's what I learned, and how to accomplish this:

use framework "Foundation"

set _plist to ...

set _objcPlist to GetAppleScriptObjectAsObjcObject(_plist)

set _value to GetObjcPropertyValueByName("MyProperty", item 1 of _objcPlist)

on GetAppleScriptObjectAsObjcObject(asObject)
    set a to current application
    set cClass to class of asObject

    if (cClass is record) then
        return a's NSDictionary's dictionaryWithDictionary:asObject
    else if (cClass is list) then
        return a's NSArray's arrayWithArray:asObject
    else
        error "Unexpected Class Type"
    end if
end GetAppleScriptObjectAsObjcObject

on GetObjcPropertyValueByName(propertyName, objcItem)
    return (objcItem's valueForKey:propertyName) as text
end GetObjcPropertyValueByName



回答2:


you may try the try ... on error approach:

set aRecord to {title:"hello world", author:"who's who"}

try
    aRecord as Unicode text
on error error_message
    set err to error_message
end try
err

-- "Can’t make {title:\"hello world\", author:\"who's who\"} into type Unicode text."

then parse err (it's text now). it depends on the complexity of aRecord, if it's a record of nested lists, or records; the parsing would be very complicated. have fun :)



来源:https://stackoverflow.com/questions/37638203/applescript-get-value-of-property-by-string-name-of-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!