(这个示例项目在这里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 的绑定是标准的:
内容
- 绑定到:阵列控制器
- 控制器键:排列对象
内容价值
- 绑定到:阵列控制器
- 控制器键:排列对象
- 模型键路径: title(排列对象数组中包含的 NSDictionary 项的键)。