If you use the NSArrayController button to populate the pop-up button (or rather its menu), then you can simply define a sort handle to handle the sort.
Getting the array controller to work with the pop-up button for the first time can be a bit complicated, but if you bind the contents of the pop-up button to the arrangedObjects array controller, and then bind the content values ββto the appropriate string property of your model objects, you should be fine.
Then adding a new element will be just a matter of adding an element through an array controller.
So, in case you are not familiar with the NSArrayController class and binding, the following is a brief description of how you can do this in Interface Builder. Suppose your items have a string property called name .
- Create a property (mutable) in your nib file owner (e.g. application delegate) to hold your items.
- Create an array controller object in Interface Builder.
- Bind your content array to the newly created array. Binding can be set in the Xcode Bindings Inspector (Cmd-Opt-7).
- Add a popup to the window.
- Set the content of the pop-up button button to the controller of the controller of the
arrangedObjects controller. This is the default option for this binding. - Set the value of the contents of the contents of the pop-up button for the controller controller
arrangedObjects and This will give the correct text in the menu. - Somewhere in your code, create a sort handle and set it on the array controller (using the
setSortDescriptors: method). To do this, you may need to determine the output for the file owner to store the array controller. - To add a new item to your popup button, use the
add: array controller method.
This should bring you to a minimum of your own code and a little magic in the Builder interface.
For fairly simple user interface elements, bindings can really save a lot of work. Read more about them here .
Edited to add an example:
For an example of how this can be done, consider an application with an application delegate that has a data property, an array of dictionaries, with a name property. Note that this is one level of abstraction deeper than your example, in which the array contains only single lines. Personally, I prefer that.
self.data = [NSMutableArray arrayWithObjects: [NSDictionary dictionaryWithObjectsAndKeys:@"Flowers", @"name", nil], [NSDictionary dictionaryWithObjectsAndKeys:@"Animals", @"name", nil], [NSDictionary dictionaryWithObjectsAndKeys:@"Trees", @"name", nil], nil];