This one gave me a bit of a hard time.
It never occured to me that to solve the puzzle I had to declare a Cocoa class as a property. And I also never read about it. Up to now, I have always considered this a mere refactoring convenience to save a lot of unnecessary typing, offered by Script Debugger under Edit > AppleScriptObjC > Migrate to Properties.
My case:
my sortList({"B", "A"})
on sortList(theList)
script o
use framework "Foundation"
on AsObjCsort(theList)
set theArray to (current application's NSArray's arrayWithArray:theList)
set theArray to theArray's sortedArrayUsingSelector:"localizedStandardCompare:"
return theArray as list
end AsObjCsort
end script
return o's AsObjCsort(theList)
end sortList
The above works.
use framework "Foundation"
my sortList({"B", "A"})
on sortList(theList)
script o
--use framework "Foundation"
on AsObjCsort(theList)
set theArray to (current application's NSArray's arrayWithArray:theList)
set theArray to theArray's sortedArrayUsingSelector:"localizedStandardCompare:"
return theArray as list
end AsObjCsort
end script
return o's AsObjCsort(theList)
end sortList
This one doesn’t.
use framework "Foundation"
my sortList({"B", "A"})
on sortList(theList)
script o
use framework "Foundation"
on AsObjCsort(theList)
set theArray to (current application's NSArray's arrayWithArray:theList)
set theArray to theArray's sortedArrayUsingSelector:"localizedStandardCompare:"
return theArray as list
end AsObjCsort
end script
return o's AsObjCsort(theList)
end sortList
The above code also does not work.
So what to do if I intend to use ASObjC also in the main, outer script?
Tried this and that to no avail. The solution came by chance: I had to declare a property referencing NSArray in the main script to make it work. Not difficult to comprehend in hindsight. But even SD’s documentation gives no hint relating to this kind of substantial difference of this kind of “code refactoring”. At least I couldn’t find any.
use framework "Foundation"
-- classes, constants, and enums used
property NSArray : a reference to current application's NSArray
my sortList({"B", "A"})
on sortList(theList)
script o
on AsObjCsort(theList)
set theArray to NSArray's arrayWithArray:theList
set theArray to theArray's sortedArrayUsingSelector:"localizedStandardCompare:"
return theArray as list
end AsObjCsort
end script
return o's AsObjCsort(theList)
end sortList
Just to spare somebody from pulling his or her hair over this.
On a side note:
I have seen scripts fail sometimes (= inconsistently) when calling script libraries containing ASObjC code if the calling script did not declare the same frameworks as the ones used in the library.
Anybody with similarly odd observations?