Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NSViewController in an NSDocument-based Cocoa app

I've got plenty of experience with iOS, but Cocoa has me a bit confused. I read through several Apple docs on Cocoa but there are still details that I could not find anywhere. It seems the documentation was written before the NSDocument-based Xcode template was updated to use NSViewController, so I am not clear on how exactly I should organize my application. The template creates a storyboard with an NSWindow, NSViewController.

My understanding is that I should probably subclass NSWindowController or NSWindow to have a reference to my model object, and set that in makeWindowControllers(). But if I'd like to make use of the NSViewController instead of just putting everything in the window, I would also need to access my model there somehow too. I notice there is something called a representedObject in my view controller which seems like it's meant to hold some model object (to then be cast), but it's always nil. How does this get set?

I'm finding it hard to properly formulate this question, but I guess what I'm asking is:how do I properly use NSViewController in my document-based application?

PS: I understand that NSWindowController is generally meant to managing multiple windows that act on one document, so presumably if I only need one window then I don't need an NSWindowController. However, requirements might change and having using NSWindowController may be better in the long run, right?

like image 522
vopilif Avatar asked Aug 31 '15 17:08

vopilif


2 Answers

I haven't dived into storyboards but here is how it works:

If your app has to support 10.9 and lower create custom of subclass NSWindowController

Document based app

Put code like this into NSDocument subclass

- (void)makeWindowControllers
{
  CustomWindowController *controller = [[CustomWindowController alloc] init];
  [self addWindowController:controller];
}

If your app has multiple windows than add them here or somewhere else (loaded on demand) but do not forget to add it to array of document windowscontroller (addWindowController:)

If you create them but you don't want to show all the windows then override

- (void)showWindows
{
  [controller showWindow:nil]
}

You can anytime access you model in your window controller

- (CustomDocument *)document
{
  return [self document];
}

Use bindings in your window controller (windowcontroller subclass + document in the keypath which is a property of window controller)

[self.textView bind:@"editable"
                  toObject:self withKeyPath:@"document.readOnly"
                   options:@{NSValueTransformerNameBindingOption : NSNegateBooleanTransformerName}];

In contrast to iOS most of the views are on screen so you have to rely on patterns: Delegation, Notification, Events (responder chain) and of course MVC.

10.10 Yosemite Changes:

NSViewController starting from 10.10 is automatically added to responder chain (generally target of the action is unknown | NSApp sendAction:to:from:) and all the delegates such as viewDidLoad... familiar from iOS are finally implemented. This means that I don't see big benefit of subclassing NSWindowCotroller anymore.

NSDocument subclass is mandatory and NSViewController is sufficient.

You can anytime access you data in your view controller

- (CustomDocument *)document
{
  return (CustomDocument *)[[NSDocumentController sharedDocumentController] documentForWindow:[[self view] window]];
  //doesn't work if you do template approach
  //NSWindowController *controller = [[[self view] window] windowController];
  //CustomDocument *document = [controller document];
}

If you do like this (conforming to KVC/KVO) you can do binding as written above.

Tips: Correctly implement UNDO for your model objects in Document e.g. or shamefully call updateChangeCount:

[[self.undoManager prepareWithInvocationTarget:self] deleteRowsAtIndexes:insertedIndexes];

Do not put code related to views/windows into your Document

Split your app into multiple NSViewControllers e.g.

- (void)prepareForSegue:(NSStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:AAPLListWindowControllerShowAddItemViewControllerSegueIdentifier]) {
        AAPLListViewController *listViewController = (AAPLListViewController *)self.window.contentViewController;

        AAPLAddItemViewController *addItemViewController = segue.destinationController;

        addItemViewController.delegate = listViewController;
    }
}

Previous code is called on windowcontroller with viewcontroller as delegate (again possible only after 10.10)

I always prefer to use multiple XIBs rather than one giant storyboard/XIB. Use following subclass of NSViewController and always inherit from it:

#import <Cocoa/Cocoa.h>

@interface MyViewController : NSViewController

@property(strong) IBOutlet NSView *viewToSubstitute;

@end

#import "MyViewController.h"

@interface MyViewController ()

@end

@implementation MyViewController

- (void)awakeFromNib
{
  NSView *view = [self viewToSubstitute];
  if (view) {
    [self setViewToSubstitute:nil];
    [[self view] setFrame:[view frame]];
    [[self view] setAutoresizingMask:[view autoresizingMask]];
    [[view superview] replaceSubview:view with:[self view]];

  }
}

@end
  1. Add a subclass of MyViewController to the project with XIB. Rename the XIB
  2. Add NSViewController Object to the XIB and change its subclass name Howto2
  3. Change the loading XIB name to name from step 1 Howto3
  4. Link view to substitute to the view you want to replace Howto1 Check example project Example Multi XIB project

Inspire yourself by shapeart or lister or TextEdit

And a real guide is to use Hopper and see how other apps are done.

PS: You can add your views/viewcontroller into responder chain manually.

PS2: If you are beginner don't over-architect. Be happy with the fact that your app works.

like image 197
Marek H Avatar answered Sep 28 '22 03:09

Marek H


I'm relatively new to this myself but hopefully I can add a little insight.

You can use the view controllers much as you would in ios. You can set outlets and targets and such. For NSDocument-based apps you can use a view controller or the window controller but I think for most applications you'll end up using both with most of the logic being in the view controller. Put the logic wherever it makes the most sense. For example, if your nsdocument can have multiple window types then use the view controller for logic specific to each type and the window controller for logic that applies to all the types.

The representedObject property is primarily associated with Cocoa bindings. While I am beginning to become familiar with bindings I don't have enough background to go into detail here. But a search through the bindings programming guide might be helpful. In general bindings can take the place of a lot of data source code you would need to write on ios. When it works it's magical. When it doesn't work it's like debugging magic. It can be a challenge to see where things went wrong.

like image 28
ac4lt Avatar answered Sep 28 '22 03:09

ac4lt