Binding to a NSViewController's representedObject - cocoa

(Abstract: bindings work in code, but not in IB)
I have a window managed by a NSWindowController. To the left of the window is a source view. To the right is a table view showing the elements of the currently selected source.
I have set up a NSTreeController within my window XIB. I want its contents to be used for the source view. It's selection will drive the table view.
I am trying to split this up using NSViewControllers. One view controller will load a NIB containing the source view. Another view controller will load the table view.
Seeing that I need access to the NSTreeController within the source view controller, I have set it to be the view controller's representedObject. (Actually for this setup to be done by the time awakeFromNib is called on the view controller, I have turned representedObject into an IBOutlet).
All works fine when I wire my source view up in code:
[outlineView bind:#"content"
toObject:sources
withKeyPath:#"arrangedObjects"
options:nil];
[outlineView bind:#"selectionIndexPaths"
toObject:sources
withKeyPath:#"selectionIndexPaths"
options:nil];
[[outlineView tableColumnWithIdentifier:#"Title"] bind:#"value"
toObject:sources
withKeyPath:#"arrangedObjects.title"
options:nil];
I am however unable to reproduce this using Interface Builder. Thing is, here the "controller key" textfield is grayed out. Thus I bind column's "value" to the file owner using a model keyPath of "representedObject.arrangedObjects.title". This does not show the desired behavior. Actually an exception is thrown: -[NSProxy doesNotRecognizeSelector:_mutatingNodes] called!
How can I use representedObject in IB?
Can I create a controller in IB which acts as proxy to representedObject?
Could I set-up a tree controller in the source view XIB which during NIB loading gets swapped out for the representedObject?

I moved away from using representedObject. It appears that is meant only for model objects.
I now pass in my tree controller using a custom outlet. I continued setting up and tearing down the bindings in code.

I’ve similar issues when I try to pass a reference to an object controller (NSTreeController in my case). I don’t think this is how Apple wants you to use their KVO-compatible controllers. The exceptions look like they’re XIB-unarchiving & timing-related.
The trick is not to pass the controllers, but to pass the underlying data and keep the selection in sync.
This way you can set up your bindings in a storyboard and won’t get any exceptions. You’ll have to set up a new instance of an object controller for every child view controller (copy & paste in Storyboard once you configured the first one works). For a detailed example take a look at another answer that gets much more into detail.

Related

Connect two NSObjectControllers within a multi view OSX Storyboard

I'm using Storyboards for the first time creating a master/detail view for a simple object.
Both view controller items of the split view have their own view & NSObjectControllers. The controller for the table view is a NSArrayController (which shows all instances of the Entity). The controller for the detail view is an NSObjectController, which shows just the selected instance.
When I click an object in the table, I'd like the detail to show up in the detail view. So I believe my goal here is to bind the 'contents' of the detail object controller to the 'selection' of the master array controller. However with storyboards I cannot cross view controller boundaries (can't create the IB 'link'. aka: can't bind cross VC).
Whats the best practice for doing this?
So far all I can think to do is manually set all this up in one of the controllers (either the root controller, window controller or perhaps the master table view controller) - but that seems counterintuitive. That seems to defeat the purpose of being able to lay out this stuff within storyboards in the first place, and my controller of choice would then have to know about the other controller specifically.
I must be missing something!

Best practice for setting a data source and delegate for a UITableView

This question may not have a straight answer, but I am curious as to what others think. I have a UIViewController and inside that I have 2 objects a UIView and and UITableView. Each object as it's own custom class. My question is about the UITableView, what object should be the datasource and the delegate. Right now I have the UIViewController set to those rolls, but is it beset practice to set the object itself to be the data source and the delegate, maybe use the method awakeFromNib to set those 2 sources. Are both ways ok? I would think that setting the data and the delegate to the class that represents the tableview would keep that code apart from the view controller, which I would think would be a good thing.. but maybe not...
Good question actually.
Look at the Controller as an example of the Mediator Pattern from the Gang of Four: it's mediating the relationship between the View and the Model. Most of the web world has gone to using binding of some sort, so you typically see model objects 'bound' directly to the view layer, e.g. a text edit field might have an expression indicating which field in the domain object it is editing, then the framework will provide the services of marshaling and unmarshaling that data.
In Cocoa, you typically don't do that: you bind to properties in the Controller, and those typically are then used to transform the underlying domain class. So for instance, if you make a storyboard and make a form and have a custom controller, now you want to edit the name of some entity, e.g. User, you would CTRL-drag from the edit box over to the source, it would make an outlet, which would then give you control not only of what appears in that box, but the control itself. Then you could add a submit button and CTRL-drag to create a method, for Save, and when that's clicked, you could update the underlying User instance.

Get index of a view inside a NSCollectionView?

I've developed an app for Mac OS X Lion using its new view-based NSTableView, but as I want to port the whole app to Snow Leopard I'm trying to figure out the best way to emulate such a tableview. So far I've created a NSCollectionView and everything is fine, except for the fact that I can't get the index of the view from which a button click event is triggered.
In Lion I have the following function:
- (IBAction)buttonClick:(id)sender
so I can get the index of the view inside the tableview using a method (I can't remember its name) like
- (NSInteger)rowForView:(NSView *)aView
with aView being the sender's superview, but I couldn't find something similar for the collection view ... The only "useful" method seems to be
- (NSCollectionViewItem *)itemAtIndex:(NSUInteger)index
(or something like this), but this can't help me as it returns a NSCollectionViewItem and I can't even access it knowing only the corresponding view!
Within buttonClick, try this code:
id collectionViewItem = [sender superview];
NSInteger index = [[collectionView subviews] indexOfObject:collectionViewItem];
return index;
Hope this helps :)
Geesh! Both of those approaches have issues. I can see how the first on may work, but note that the "collectionViewItem" is actually the view, NOT the collectionViewItem, which is a view controller.
The second way will not work, unless you subclass the button and put in a back link to the collectionViewItem. Otherwise, your view does not know what collectionViewItem controls it. You should use a selector binding to the collectionViewItem's representedObject instead, to get the action to the correct object in your array.
How about something like:
id obj = [collectonViewItem representedObject];
NSInteger index = [[collectionView contents] indexOfObject:obj];
As I suggested here: How to handle a button click from NSCollectionView
I would do it like this (because the button you want to press should be coupled with the corresponding model, therefore the represented object):
Add a method to the model of your collectionViewItem (e.g. buttonClicked)
Bind the Button Target to Collection View Item
While binding set model key path to: representedObject
While binding set selectorname to: methodname you chose earlier (e.g. buttonClicked)
Add protocol to your model, if you must tell delegate or establish observer-pattern
use NSArrayController for binding to NSCollectionView,
use collectonViewItem.representedObject to get a Custom Model defined by yourself.
save and get index in your custom model.
That's works for me.

Switching between NSViewControllers

I'm developing a Mac Application. The application has a common source view on the left and a detail view on the right which is the main part of the whole window.
It's like a Master-Detail relationship, but each element in the source view require another detail view. In fact, I have designed a specific NSViewController for each element in the source view.
If I'm switching between these NSViewControllers, that means If I select another element in the source view, I remove the current view and add the view of the newly selected NSViewController. Everytime I change the NSViewController, its state will be lost. When the user comes back to that NSViewController, he has to start over.
My question now is: How can I save the state of the NSViewController, so that I can switch between these without losing its states and can continue where I have left?
Two considerations about your problem:
Keep model data in model classes. This means that you can always recreate a view controller and set its represented object provided the model classes have kept the changes made via the view controller. When you need to instantiate a view controller, set its represented object to (a representation of) a model class.
When removing a view from its superview, you do not necessarily need to release its corresponding view controller. Instead, you can keep strong references to all view controllers in your window controller/application delegate, so no state is actually lost.
Use NSArchiver. Implement archiving/unarchiving in your dealloc/init methods and store each view controller's state in a file named after the class (if you have one item per view controller policy). Otherwise think of some simple naming convention and use it.

Cocoa bindings problem; bound table columns don't show any data, no errors in console

I'm having trouble converting my Cocoa project from a manually-synched interface model to a bindings model so that I don't have to worry about interface glue code.
I followed the CocoaDevCentral Cocoa Bindings tutorial to make sure that I had covered all the bases, but things aren't working correctly. I have a master-detail interface, but I'm having trouble even getting the master portion of the interface to work correctly. No data is showing up in the master column, even though I've set up the bindings model similar to how it is shown in the tutorial. I've made sure all my controllers and objects have -(id)key and -(void)setKey:(id)key methods so that they're bindings-compliant, I've created a ControllerAlias object in my nib, connected it to my controller, created an NSArrayController that binds to one of the NSMutableArrays from the class that ControllerAlias connects to, made sure to set the type of objects that are contained within the array, and then I've bound a table column to the NSArrayController.
I'm getting no errors whatsoever in the Console, and setting NSBindingDebugLogLevel to 1 doesn't produce any errors either, that would help me figure out what the problem is.
The only other thing I could think of to make sure that things are working correctly is to check that the NSMutableArray that connects to the NSArrayController actually has something in it, and it does.
Any suggestions? What other typical pitfalls are there with Cocoa bindings that I should check?
Have you put a breakpoint in your key: method to determine if it is getting called or not? If it isn't, then that would indicate that something isn't set up correctly for the binding in the table column (since you have verified that your array does have items in it).
I don't think that you need to create an Object Controller anymore (that tutorial is a bit out of date). Just create an Object in your NIB, and set its class to your Controller class. You can set up the bindings directly through it instead of the ObjectController.
To set up a binding, I do the following:
Create an instance of my controller in the NIB.
Create an NSArrayController, bind it to an array in my controller.
For each column in the table, bind the value to a member of an object in the array controller.
That should be all that you need to do - I think they've cleaned this up quite a bit since bindings were first introduced a few versions ago.
I've created a ControllerAlias object in my nib,
What is a “controller alias”? Is this a model, controller, or view?
connected it to my controller,
What do you mean?
created an NSArrayController that binds to one of the NSMutableArrays from the class that ControllerAlias connects to,
Classes don't have NSMutableArrays.
What property of the array controller did you bind?
What object did you bind it to?
What key path of that object did you bind it to?
… and then I've bound a table column to the NSArrayController.
What property of the table column did you bind?
Which property (key path) of the array controller did you bind it to?
So in my original code, I was modifying the array (which the NSArrayController was representing) in awakeFromNib, not in init, so the changes weren't being reflected in the interface since I wasn't modifying the array via a key-value observing method.
I changed the code from
theArray = [[NSMutableArray alloc] init];
[theArray addObject:newThing];
to:
theArray = [[NSMutableArray alloc] init];
NSMutableArray *bindingsCompliantArray = [self mutableArrayValueForKey:#"things"];
[bindingsCompliantArray addObject:newThing];
I think the other solution is to do the loading in the -(id)init method instead of the -(void)awakeFromNib method, but that required a larger refactor, so I didn't do that.
I figured this out by adding a button to create a new thing in the array list via the NSArrayController, and when I clicked the button, a new thing was added to the array and my existing array magically showed up as well.

Resources