【发布时间】:2014-02-15 04:15:29
【问题描述】:
(这个示例项目在这里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 的绑定是标准的:
-
内容
- 绑定到: 数组控制器
- 控制器键:排列对象
-
内容价值
- 绑定到: 数组控制器
- 控制器键:排列对象
- 模型键路径: 标题(排列对象数组中包含的 NSDictionary 项的键)。
【问题讨论】:
-
为什么不创建一个 NSDictionary 并添加到数组控制器中?
-
我刚刚在上面更新了。这是你的意思吗?这样做会产生类似的情况,您仍然会得到整个数组的
-description。
标签: macos cocoa cocoa-bindings nsarraycontroller nspopupbutton