(此示例项目位于https://github.com/danieljfarrell/BindingToPopUpButtons)
我刚刚进入绑定,但我有一个NSPopUpButton绑定到一个NSArrayController,它正在我的AppDelegate(模型)中管理一个内容数组,一切正常!但是它仅适用于在-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的方式正确地改变内容数组?
// 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的绑定是标准的:
内容
内容价值
答案 0 :(得分:2)
我认为Volker意味着为你创建一个NSArrayController的插座并做这样的事情
NSMutableDictionary *song = [NSMutableDictionary dictionaryWithDictionary:@{@"title": newSong}];
[[self myArrayController] addObject:song];