Have an NSSegmentedControl and I am trying to attach different representedObject's to each NSSegmentedCell. I think I may be doing something incorrectly because it does not appear to be working.

[mySegmentedControl setSelectedSegmented:0];
[mySegmentedControl selectedCell] setRepresentedObject:myObject0];

[mySegmentedControl setSelectedSegmented:1];
[mySegmentedControl selectedCell] setRepresentedObject:myObject1];

?

Then I thought it would be as simple as:

[mySegmentedControl setSelectedSegment:0];
myObjectType *type = (myObjectType *)[[mySegmentedControl selectedCell] representedObject];

Does not appear to be working though? Am I doing something incorrectly? My issue appears to be that:

[[mySegmentedControl selectedCell] representedObject] 

always seems to the latest object that I attached. So if I select Segment 0 and it will return the representedObject that I attached for segment 1. Any ideas why?

1

There are 1 best solutions below

1
On BEST ANSWER

The selectedCell is inherited from NSControl. From the documentation:

The default implementation of this method simply returns the control's associated cell (or nil if no cell has been set). Subclasses of NSControl that manage multiple cells (such as NSMatrix and NSForm) must override this method to return the cell selected by the user.

However, NSSegmentedControl does not manage multiple cells, it's just one cell for the whole control. This is why it doesn't behave the way you'd imagine (for NSSegmentedControl, it always returns the cell of the control, so mySegmentedControl.selectedCell == mySegmentedControl.cell).

So when you call [[mySegmentedControl selectedCell] setRepresentedObject:myObject1]; you're overwriting the previously set represented object, since you always get the same cell instance.

One way to solve this is to have NS(Mutable)Array or NS(Mutable)Dictionary (with a NSNumber of the index as key, as in myDict[@(index)]) where you store the "represented" objects. You could then assign this array or dictionary as the represented object of your segmented cell:

mySegmentedControl.cell.representedObject = representedArrayOrDict;