Improving NSDocument's sheet handling

NSDocument has handy little method: -windowForSheet. Its main purpose is to figure out, when the doc has multiple windows associated with it, which is most appropriate for displaying a sheet.

I’ve found it does have one downside: what if your document is already displaying a sheet? Under such circumstances, the document’s window is still returned, leaving the system no option but to futilely beep as it fails to present a second a sheet.

This is of particular importance with Lion’s new document saving model. If a document is locked and you try to edit it, a sheet comes down informing you that the document is locked, and giving a chance to recover by unlocking, duplicating, or cancelling (performs an undo op). All very well until it happens the edit being made is in a sheet over your document window. Cocoa tries to present that error sheet and fails, leaving the edit intact. This could be just about excusable were it not for the fact that then attempting to undo the edit confuses the system further, bringing that very same warning sheet up, despite the fact you are trying to go back to the unedited state!

Well fear not, here’s a simple tweak you can implement in your document subclass to adjust the default behaviour:

There is of course one potential problem: If you have code that repeatedly tries to show a sheet, regardless of what’s onscreen already, you can end up with quite a stack of sheets, whereas before it was less obtrusive with the secondary sheets just causing a beep. Hopefully your code doesn’t do anything quite so daft as this, but I have found that a failed autosave can trigger this behaviour, should you ignore the initial error and keep switching between apps.

© Mike Abdullah 2007-2015