From the Mac OS X Application Programming Guide, “Initializing a New Document” (emphasis added):
If you override
init, make sure that your override never returnsnil.
Returningnilcould cause a crash (in some versions of AppKit) or
present a less than useful error message. If, for example, you want to
prevent the creation or opening of documents under circumstances
unique to your application, override a specificNSDocumentController
method instead.
From Xcode’s auto-generated MyDocument.m:
- (id)init
{
self = [super init];
if (self) {
// Add your subclass-specific initialization here.
// If an error occurs here, send a [self release] message and return nil.
}
return self;
}
Why does Apple give conflicting advice here?
The general idiom is that
-initmay release self and return nil if an error occurs. The document you’re citing for “never return nil” is specifically talking about subclassingNSDocument. Basically, returning nil is fine in the general case, but it’s a bad idea forNSDocumentspecifically. The template file for MyDocument.m doesn’t know about the NSDocument case, it’s just giving you the general-purpose template for the-initmethod.