3

I can access an app-wide delegate instance using [NSApp delegate] after adding an NSObject to the mainmenu.xib, setting the name of the object to the name of my appDelegate and setting the mainmenu.xib delegate to this object.

Now, what I would like to do, is to access to an object's Document, i.e. the active NSDocument that the object "belongs" to. It would be a doc-wide delegate instance I guess. Sometimes [self document] works, but not always. Is there a generic way?

Carelinkz
  • 936
  • 8
  • 27

3 Answers3

6

There is no need to pass a reference explicitly. You may access the document from NSViewController in the following way:

id document = self.view.window.windowController.document;
Vadim
  • 9,383
  • 7
  • 36
  • 58
  • ... and judging by the path, I should be able to do this in `init`, right? – Carelinkz Aug 12 '12 at 22:18
  • 1
    No, your view should be related to some window. Only then you can access that window's controller. – Vadim Aug 12 '12 at 22:45
  • Forgive my greenness, but... I instantiate a viewcontroller from myDocument. The new window is shown only when I request it, so would `windowControllerDidLoadNib:` be the right place? – Carelinkz Aug 13 '12 at 08:09
  • I believe it is not very good idea to create a `viewController` in the `NSDocument` subclass which should be responsible for data. The best place to create a view controller and insert its view into the window would be `-[NSWindowController loadWindow]`. Later, you can access the view from `NSDocument` as `self.mainWindowController.contentViewController.view`. – Vadim Aug 13 '12 at 14:51
1

What about [[NSDocumentController sharedDocumentController] currentDocument] ?

Be careful nevertheless. Please read NSDocumentController currentDocument returning nil

Community
  • 1
  • 1
Colas
  • 3,473
  • 4
  • 29
  • 68
0

For any sub windows that are part of the document, it turns out that it's very easy to make a very simple subclass of NSViewController and store the required information in there. These view controllers are set up within the main Document implementation so it is easy to pass the address of the NSDocument object. Any actual subview can then be controlled by a view controller that is a subclass of this "managing controller".

This solution does not work for every object, but it does take the biggest hurdle and solves my problem...

Carelinkz
  • 936
  • 8
  • 27