How do I get the selected item from NSPopUpButton?

subdiox picture subdiox · Aug 5, 2013 · Viewed 9.3k times · Source
property myPopUp : missing value
on startbuttonpressed_(sender)
    if myPopUp's selectedItem = "Item 1"
        display dialog "This is Item 1"
    else
        display dialog "Failed"
    end if
end startbuttonpressed_

I compiled this code successfully, but I got the message "Failed" though I selected "Item 1".
I think my mistake is "myPopUp's selectedItem", but I don't know how to correct it.
How do I get the selected item from NSPopUpButton?

Answer

scohe001 picture scohe001 · Aug 7, 2013

If you take a look at the NSPopUpButton documentation you'll be able to see all of the methods you can call and what it inherits from. Under Getting User Selection you have:

– selectedItem
– titleOfSelectedItem
– indexOfSelectedItem
– objectValue

Of course these are all methods, so if you wanted to get the index of the value selected, you'd call if like:

set my_index to myPopup's indexOfSelectedItem()

Looking at the indexOfSelectedItem entry in the docs:

indexOfSelectedItem
Returns the index of the item last selected by the user.

- (NSInteger)indexOfSelectedItem

Return Value
The index of the selected item, or -1 if no item is selected.

We get an overview of the function on top, and then the function's usage, and lastly, a description of the return value. This is telling us that indexOfSelectedItem does not take any parameters (if it did it would look something like - (NSInteger)indexOfItemWithTitle:(NSString *)title). The return value, to the left, is going to be an NSInteger, NOT an Applescript Integer. Although Applescript may be able to treat it the same way, in some situations this can give you problems. The solution is to never treat an NSString like an AS String and to never treat an NSInteger like an AS Integer. To make the conversion we'd have to change it into an AS string and then to an AS integer:

set my_index to ((myPopup's indexOfSelectedItem()) as string) as integer

Thus for your code if looks like you could use either indexOfSelectedItem or titleOfSelectedItem