2014-02-15 51 views
0

(這個例子項目是在這裏https://github.com/danieljfarrell/BindingToPopUpButtons綁定的NSMutableArray到NSPopUpButton和插入新的價值

我剛剛進入結合,但我有綁定到一個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的綁定是標準:

  • 內容

    • 綁定到:陣列控制器
    • 控制器關鍵: arrangedObjects
  • 內容價值

    • 綁定到:陣列控制器
    • 控制器關鍵: arrangedObjects
    • 型號關鍵路徑: title(包含在arrangeObjects數組中的NSDictionary項的關鍵字)。
+0

你爲什麼不創建一個NSDictionary中,並添加到陣列控制器? – Volker

+0

我剛剛更新過。這是你的意思嗎?這樣做會產生類似的情況,你仍然會得到整個陣列的'-description'。 –

回答

2

我覺得沃爾克對你意味着NSArrayController的創造的出口,並且做這樣的事情