I've got a custom NSView that I've made up. Basically, for each item in a tree view that I select, I want to swap the view out with another one.
My question is, should I be using something like NSArrayController for this? If so, how do you hook up a custom NSView to use NSArrayController and swap between views based on selections in an NSTreeView?
You could use an NSArrayController
to do this however there's a couple points you'll have to consider:
Each NSView
should be controlled by an NSViewController
, hence you're better off storing some identifier in your NSArrayController
from which you can deduct both the controller class and the associated NIB. Once you have the NSViewController
class name, you can instantiate it and load the accompanying view with the initWithNibName:
method.
It's probably a good idea to introduce the concept of a "current controller". That way you'll only have one controller (with associated view and model object graph) in memory at any time. Once you swap controllers based on the selection in the tree view, the old controller and all its associated objects will be released from memory.
Example:
NSArrayController
: @"Customers"
@"CustomersViewController"
@"CustomersView"
By storing @"Customers"
in your array you can deduct the correct controller class name and the associated NIB:
NSString *aControllerName = [anIdentifier stringByAppendingString: @"ViewController"];
NSString *aNibName = [anIdentifier stringByAppendingString: @"View"];
Class aControllerClass = NSClassFromString(aControllerName);
[self setCurrentController: [[aControllerClass alloc] initWithNibName: aNibName bundle: [NSBundle mainBundle]]];
In the above code anIdentifier
would hold the value @"Customers"
and could originate from your NSArrayController
. self
in the above example refers to your top level controller (its class depends on your design).
The actual swapping of views can be done as follows:
[[self currentController] view] removeFromSuperView];
... do swapping ...
[[self view] addSubview:[[self currentController] view]];
If you store the identifier with the data source that populates your tree view you would probably not need a separate NSArrayController
as you can then directly take the identifier from the selected object from your tree view.