SelectionIndexes on NSArrayController returns only value

I have an NSCollectionView whose contents are being processed by NSArrayController. NSCollectionView can be selected, and I need to get a list of selected items. I try to observe the NSArrayController "selectionIndexes" key property, but it just returns ALWAYS to me the value of the first item in the CollectionView, not the selected items.

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if([keyPath isEqualTo:@"selectionIndexes"]) { //True if in the array controller of the collection view really exists at least a selected object if([[arrayController selectedObjects] count] > 0) { NSLog(@"Selected objects: %@", [arrayController selectedObjects]); } else { NSLog(@"Observer called but no objects where selected."); } } } 

UPDATE

I never call this method if I manually call NSLog (@ "Selected objects:% @", [arrayController selectedObjects]) I get this

The result is always something like this

END UPDATE

 2011-07-05 20:44:45.711 collectionView2[2153:903] Selected objects 1: ( "<Hormiga: 0x10013e330>" ) 

I think I did something wrong related to NSArrayController with NSCollectionView. What could be my fault? Tell me if you want more information, I can even publish the whole program in zip if you need it.

UPDATE 2

This is the code that I use in my controller to monitor the controlController "selectionIndexes" key.

 [arrayController addObserver:self forKeyPath:@"selectionIndexes" options:NSKeyValueObservingOptionNew context:nil]; 

UPDATE 3

One of the problems was fixed, I forgot to set the binding between NSArrayController and NSCollectionView with respect to the "selectionIndexes" key. Now I can manually load the selectedObject list and its correct!

My last problem is that I do not get notification when selectionIndexes changes. So watchValueForKeyPath: ofObject: change: context: never get called!

UPDATE 4

I tried to set an observer in the init method of my controller, but thus arrayController is still null. Moving addObserver to awakeForNib solved all my problems!

+6
source share
1 answer

If you want the indexes of the blocks of array controllers to synchronize with the views of the collection, you also need to link them. In short:

  • Bind a view of the Content collection to an array controller, arrangedObjects
  • Bind the Selection Indexes view of the Selection Indexes collection to the array controller, the selectionIndexes key.

Also, make sure arrayController been installed before adding an observer. It is guaranteed that the outputs must be set in -awakeFromNib and other methods that are called after it: if you use a window controller, you can use -windowDidLoad ; if you use a view controller, you can use -loadView ; otherwise -applicationDidFinishLaunching: in application deletion.

+10
source

Source: https://habr.com/ru/post/892068/


All Articles