Cocoa Scripting: Accept and return NSData

流过昼夜 提交于 2019-12-05 15:04:58

Shane Stanley did indeed know a way, and it does not even require extra code in my app - instead, it can all be done in AppleScript, with these two conversion functions:

use framework "Foundation"

set nsData1 to current application's NSData's dataWithContentsOfFile:"/etc/hosts"
set asData to my ASDataFromNSData(nsData1)
set nsData2 to my NSDataFromASData(asData)

on ASDataFromNSData(theData)
    set theCode to current application's NSHFSTypeCodeFromFileType("'rdat'")
    return (current application's NSAppleEventDescriptor's descriptorWithDescriptorType:theCode |data|:theData) as data
end ASDataFromNSData

on NSDataFromASData(asData)
    return (current application's NSArray's arrayWithObject:asData)'s firstObject()'s |data|()
end NSDataFromASData

It appears that rdat is a special AppleScript type for this purpose, with the framework automatically handling the conversion with NSData. I can't find that type declared in the AE.framework's headers, though.

I then still have to handle this rdat type explicitly in my app's code, though. But I won't need the value-type in the sdef, and can change the property to:

<property name="raw data" code="rawD" type="any">
    <cocoa key="rawData"/>
</property>

Returning data as rdat is similar. My -rawData method:

return [NSAppleEventDescriptor descriptorWithDescriptorType:'rdat' data:myNSData];

This only works if I declare the property type as "any", though. If I use type="rdat", Script Debugger shows the type as a dedicated raw data type, but then I get -10000 errors when trying to set or get the property in a script.

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