Question

(This example project is here https://github.com/danieljfarrell/BindingToPopUpButtons)

I'm just getting into binds, but I have an NSPopUpButton bound to a NSArrayController which is managing a content array in my AppDelegate (model) and all works well! However it only works well for static objects which are added to the content array in the -init method. I have problems when I mutate the content array (inserting, adding etc...).

Songs loaded in -init

// AppDelegate.m
- (id)init
{
    self = [super init];
    if (self) {
        _songs = [[NSMutableArray alloc] init];
        NSMutableDictionary *song1 = [NSMutableDictionary dictionaryWithDictionary:@{@"title" : @"Back in the USSR"}];
        NSMutableDictionary *song2 = [NSMutableDictionary dictionaryWithDictionary:@{@"title" : @"Yellow Submarine"}];

        [_songs addObjectsFromArray:@[song1, song2]];
    }
    return self;
}

Problem. When I mutate the content array using -mutableArrayValueForKey: by inserting a new song the NSPopUpButton displays the -description of the array rather than the value of the array elements and also the array seems to be duplicated? For this simple case where the model is just a NSMutableDictionary how can I properly mutate the content array in an KVO compliant way?

Mutating the data source

// AppDelegate action method from button click
- (IBAction)addNewSong:(id)sender {

    // Grab the new song title from a text field
    NSString *newSong = self.songTextField.stringValue;
    // Grab the insert index from a text field.
    NSInteger index = self.indexTextField.integerValue;

    /* Here I want the array controller to
       create a new NSMutableDictionary
       and set the title key with the new song. */
    [[self.songs mutableArrayValueForKey:@"title"] insertObject:newSong atIndex:index];

    /* I also tried adding a dictionary but ran into a similar problem...*/
    // [[self.songs mutableArrayValueForKey:@"title"] insertObject:[@{@"title" : newSong} mutableCopy] atIndex:index]; 
}

The bindings for the NSPopUpButton are standard:

  • Content

    • Bind to: Array Controller
    • Controller key: arrangedObjects
  • Content Value

    • Bind to: Array Controller
    • Controller key: arrangedObjects
    • Model key path: title (the key of the NSDictionary items contained in the the arrangedObjects array).
Was it helpful?

Solution

I think Volker means create an outlet for you NSArrayController and do something like this

NSMutableDictionary *song = [NSMutableDictionary dictionaryWithDictionary:@{@"title": newSong}];

[[self myArrayController] addObject:song];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top