macos - 将 NSMutableArray 绑定(bind)到 NSPopUpButton 并插入新值

标签 macos cocoa cocoa-bindings nsarraycontroller nspopupbutton

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

我刚刚进入绑定(bind),但我有一个绑定(bind)到 NSArrayController 的 NSPopUpButton,它正在我的 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 的绑定(bind)是标准的:

  • 内容

    • 绑定(bind)到:数组 Controller
    • Controller 键:排列对象
  • 内容值(value)

    • 绑定(bind)到:数组 Controller
    • Controller 键:排列对象
    • 模型键路径:标题(arrangedObjects 数组中包含的 NSDictionary 项的键)。

最佳答案

我认为 Volker 的意思是为你的 NSArrayController 创建一个 socket 并做类似的事情

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

[[self myArrayController] addObject:song];

关于macos - 将 NSMutableArray 绑定(bind)到 NSPopUpButton 并插入新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21793316/

相关文章:

iphone - 如何让一段代码在单独的线程中运行?

ios - OS X 核心绑定(bind)在使用 Storyboard 时不保存核心数据

objective-c - 经验丰富的 Cocoa 程序员在多大程度上依赖 Interface Builder 来连接他们的应用程序?

iphone - 无法释放 CGContextRef(上下文来自 CGLayer)

Mac Os High Sierra 上的 Java RE 6

cocoa - NSString stringWithFormat : with random number of replacements

objective-c - Cocoa Binding 仅用于检索

ios - cocoa 绑定(bind) coredata 中的延迟获取是什么?

macos - 在 MacOS 中使用鼠标和热键 move 窗口

ios - 强制单轴速度