(此示例项目位于 https://github.com/danieljfarrell/BindingToPopUpButtons )
我刚刚进入绑定(bind),但我有一个绑定(bind)到 NSArrayController 的 NSPopUpButton,它正在我的 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 的绑定(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/