Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

applescript - getting an index of a selected item in a list apple script

I'm trying to write an apple script with a large list and I want to prompt the user to select an item from the list and then the script should display an index of this item. Getting the script to prompt the user to select from list wasn't a problem, but I can't get an index of a selected list item.

Here is the example code and a loop I tried so far

set cities to {"New York", "Portland", "Los Angelles", "San Francisco", "Sacramento", "Honolulu", "Jefferson City", "Olimpia"}
set city_chooser to choose from list cities
set item_number to 0
repeat with i from 1 to number of items in cities
    set item_number to item_number + 1
    if i = city_chooser then
        exit repeat
    end if
end repeat
display dialog item_number

It just gives me the number of items in the list.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Vanilla AppleScript does not provide an indexOfObject API. There are three ways:

  1. An index based loop which iterates the list and returns the index when the object was found.
  2. Bridging the list to AppleScriptObjC to use the indexOfObject API of NSArray.
  3. If the list is sorted a binary search algorithm which is very fast.

A fourth way is to populate the list with this format

1 Foo
2 Bar
3 Baz

and get the index by the numeric prefix but this is quite cumbersome for large lists.


Edit:

There are a few issues in the code. The main two are that choose from list returns a list (or false) and you are comparing a string with the index variable, an integer.

Try this

set cities to {"New York", "Portland", "Los Angeles", "San Francisco", "Sacramento", "Honolulu", "Jefferson City", "Olympia"}
set city_chooser to choose from list cities
if city_chooser is false then return
set city_chooser to item 1 of city_chooser
repeat with i from 1 to (count cities)
    set city to item i of cities
    if city = city_chooser then exit repeat
end repeat
display dialog i

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...