Search code examples
objective-ccocoanscollectionviewnscollectionviewitem

Cocoa- Using representedObject for NSButton in NSCollectionView


Setup

I have a NSCollectionView. I have a checkbox in the View Prototype. I've successfully set up bindings so the Card Title and action get populated. (image 1, below)

Goal

I'd like, when I click the checkbox, to run a function that accesses the specific CardModel that the View Prototype is already able to access. I'll then manipulate its data accordingly.

Research

I found this article on SO: Get the representedObject values of NSCollectionViewItem NSButton click, which describes my situation pretty well. The answer, unfortunately, is without specific code. Here's what's suggested:

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.

Seems simple enough, right?

Attempted Solution(s)

I create a method cardCheckBoxClicked: and connect it to the checkbox.

As per the advice above, I connect the button cell's outlet representedObject to Card Collection View Item. (image 2)

I then attempt to get the Card Collection View Item's representedObject in code.

From MainWindowController.h:

-(IBAction)cardCheckBoxClicked:(id)sender
{
    CardModel* cModel = [[sender representedObject] representedObject];

    NSLog(@"card title: %@",cModel.title);
}

Error

When I click on the checkbox, I get the following error:

-[NSButton representedObject]: unrecognized selector sent to instance 0x6080001581b0

Question!

So - how do I access the button cell's represented object? Did I misunderstand the advice given above? How can I successfully access the data I need?

Images (reference)

bindings example enter image description here

represented object connection enter image description here


Solution

  • This here:

    -[NSButton representedObject]:
    

    Is you asking the Class NSButton to run the method representedObject. Make sure you distinguish between a Class an an object or instance of that class.

    You need to take the actual button, get its button cell, (at least I think that's what you want), and then call representedObject on the cell. If I am understanding you correctly. I never touch interface builder, so here's completely made up code that lines up with what you are asking for.

    someObject = [[theButton cell] representedObject];