Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDocumentController currentDocument returning nil

I'm working on my first Mac document-based application.

I have subclassed NSDocument, reimplementing methods such as

- (BOOL)readFromURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError;
- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError;
- (void)makeWindowControllers;

The main window controller is a subclass of NSWindowsController, that contains two NSViewController subclasses.

The problem I'm facing is that I need to have access to the current document from these view controllers. What I do is calling

MyDocument *myDocument = [[NSDocumentController sharedController] currentDocument];

At first, right after starting the application, a new document is created. Then, the main window and its view controllers are created, but the method above returns nil. Here's the log (using NSLog) I get:

Just created this new document: <MyDocument: 0x10040ff10>
I'm in a view controller and current document is (null)

After that, creating a new document and calling this method results in a non-nil pointer, but it doesn't point at the right document, but to the first one:

Just created this new document: <MyDocument: 0x100437e10>
I'm in a view controller and current document is <MyDocument: 0x10040ff10>

Notice that after the second document creation, currentDocument points to the first document and not to the second one.

Any idea of what I'm missing or doing wrong here? When is currentDocument set for NSDocumentController?

like image 276
msoler Avatar asked Jan 18 '12 15:01

msoler


1 Answers

From the Apple documentation on NSDocumentController currentDocument it says:

This method returns nil if it is called when its application is not active. This can occur during processing of a drag-and-drop operation, for example, in an implementation of readSelectionFromPasteboard:. In such a case, send the following message instead from an NSView subclass associated with the document:

[[[self window] windowController] document];

This is slightly vague as it doesn't really qualify what "not active" means. It could be that a drag 'n drop operation is the only trigger but it doesn't state whether that's the only trigger for an app to become not active.

Maybe the suggested alternative by Apple is of use to you.

like image 125
Roger Avatar answered Nov 15 '22 23:11

Roger