1

I have read some questions and I find some very confusing and I don't really know if they answer my question.

I have an NSCollectionView implemented and connected to a Core Data context, everything shows correctly.

Now what I have is buttons in the view prototype, and when I click this buttons I need to get the value of the representedObject of that cloned view.

I have read and read and some parts are confusing to me, so I'm looking for a simple explanation.

Thank you for your time.

Eun
  • 4,146
  • 5
  • 30
  • 51
Rageofflames
  • 35
  • 1
  • 12

1 Answers1

8

An action method takes one argument:

- (IBAction) collectionViewButtonClicked:(id)sender {
}

That sender is the control or other UI element (e.g., menu item) that sent the message.

With that argument, when your action method gets called, you know which button was clicked.

A button is a kind of control, and every control is backed by at least one cell. Cells have represented objects, too.

So, first, set the represented object of your button's cell to the collection view item that owns the button. (You can do this in the nib editor.) Then, in your action method, get the button's cell, then the cell's represented object (which is the item), then the item's represented object.

If the representedObject outlet doesn't show up in the nib editor, you probably have the button selected, not its cell. I recommend opening the nib editor's outline view using the button in the lower-left and then never, ever closing it.

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
  • Hi Peter, thank you for your time and your answer, you were very crystal clear! I will test your answer and it's probably what I seek. Thanks again. – Rageofflames Mar 18 '13 at 09:43
  • Hi again Peter, well your solution worked just fine, thank you very much for your time and effort to explain me everything in an easy way to understand. I can't up vote your answer cause I'm new here but I will mark it has an answer and a very good one, I am sure more people will use this. Thanks again. – Rageofflames Mar 18 '13 at 14:50
  • 1
    `DesiredItem* myItem = [[[sender cell] representedObject] representedObject];` – ryantuck Jul 03 '14 at 14:35
  • 1
    @RyanTuck: `DesiredItem` is probably not a good name for the example model/value class (“item” could be mistaken to refer to the collection view item, whereas the result of this chain of messages is the value object or model object it represents), but otherwise, yeah. – Peter Hosey Jul 04 '14 at 05:18
  • You are the Titan of Objective C! Thank you, this solution just works! – Serge Velikan Jul 05 '14 at 20:57
  • 1
    @PeterHosey, agreed. I had tried my hand using your solution and ran into trouble until realizing I should be calling the `representedObject` of `[sender cell]` instead of just `sender`, so thought I'd post the code to help others in the future. – ryantuck Jul 07 '14 at 22:51