While working on making my Mac app scriptable, I ran into another confusing concept with AppleScript about it be able to store elements with their content.
Let’s assume my app maintains a list of Persons. I can now do this:
delete every person -- clears the list
make new person with properties {name:"Adam"} at beginning -- makes a person at pos 1 with ID "p1"
make new person with properties {name:"Bob"} -- makes a person at pos 2 with ID "p2"
Now I would like to swap these two in their order. I could do this:
move person 2 to beginning
That’s fine. However, swapping is not really what I want to do - I want to do how AppleScript holds on the data. So here’s the challenge:
This would be an alternative way to swap items in more classic programming languages:
set savedPerson to person 2
delete person 2
set beginning of persons to savedPerson
This does not work, however. (I tried to compare this to how it would work with a list of strings, but I cannot seem to even use “delete” on items in such a list. Odd.)
As far as I see it, it’s not working because the savedPerson is, at least from my app’s view, not existing any more:
I.e. after the delete command, AppleScript (or rather the Cocoa Scripting framework) will ask me to tell it the index of the item with ID “p2”. While I may still have a hold on the object with ID “p2”, I cannot return an index to it because it’s not existing in the list that the container (here: the app) maintains. It still exists but I cannot tell Cocoa Scripting how it can address it because it only knows of items in arrays, and it’s been removed from there.
Should this work (i.e. am I doing something wrong again)? E.g., do I need to maintain a hidden elements array that still keeps the items around even if they’re not in the visible list?
Or is my code using the wrong way to retrieve and hold on to an element that gets deleted from a list? How is it done?
Again, I am not looking for ways to swap items, I am trying to understand how one can hold the contents of an element after it gets deleted from its source, so that said element can later be re-inserted, maybe even into another list.
One more thing - the said items I want to be able to store this way are not just having properties (if that were the case, I could probably just get all properties and then later recreated an element using “make new” with the saved props. But in my case, the element also has child elements, and so on, so it’s a whole tree I have dangling there after the delete from the list, and I want to keep that tree around in Applescript and later assign that to a list again.