将NSMutableArray绑定到NSPopUpButton并插入新值

时间:2014-02-15 04:15:29

标签: macos cocoa cocoa-bindings nsarraycontroller nspopupbutton

(此示例项目位于https://github.com/danieljfarrell/BindingToPopUpButtons

我刚刚进入绑定,但我有一个NSPopUpButton绑定到一个NSArrayController,它正在我的AppDelegate(模型)中管理一个内容数组,一切正常!但是它仅适用于在-init方法中添加到内容数组的静态对象。当我改变内容数组(插入,添加等等)时,我遇到了问题。

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;
}

问题即可。当我使用-mutableArrayValueForKey:通过插入新歌来改变内容数组时,NSPopUpButton会显示数组的-description而不是数组元素的值,而且数组似乎也是重复的?对于这个模型只是NSMutableDictionary的简单情况,我怎样才能以符合KVO的方式正确地改变内容数组?

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]; 
}

NSPopUpButton的绑定是标准的:

  • 内容

    • 绑定到:阵列控制器
    • 控制器密钥: arrangeObjects
  • 内容价值

    • 绑定到:阵列控制器
    • 控制器密钥: arrangeObjects
    • 模型键路径: title(arrangeObjects数组中包含的NSDictionary项的键)。

1 个答案:

答案 0 :(得分:2)

我认为Volker意味着为你创建一个NSArrayController的插座并做这样的事情

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

[[self myArrayController] addObject:song];