6
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?

subdiox
  • 387
  • 2
  • 14

2 Answers2

21

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

scohe001
  • 15,110
  • 2
  • 31
  • 51
  • Thank you. But "set my_index to myPopup's indexOfSelectedItem()" also worked. I wrote my codes Without integer cast. I solved this problem. – subdiox Aug 07 '13 at 23:58
  • @user2648576 Like I said, from my experience that will work maybe 75% of the time. It saves a lot of headache and debugging to simply cast every NSInteger and NSString and then not have to worry about AS freaking out at the Obj-C – scohe001 Aug 08 '13 at 00:01
  • So, if I write "set my_index to ((myPopup's indexOfSelectedItem()) as string + 1) as integer", will this succeed? – subdiox Aug 08 '13 at 09:59
  • Once you convert it to a string you'll have something like "5", so you're trying "5"+1. Add the plus one after you've converted it into an integer and you're done casting. – scohe001 Aug 08 '13 at 13:38
3

The if condition should be like this:

if (myPopup's titleOfSelectedItem()) = "Item 1" then
Michele Percich
  • 1,872
  • 2
  • 14
  • 20