What if [super init] returns nil?

Take the following code as an example.

- (id)init {
    self = [super init];
    if (self) {
        // code
    }
    return self;
}

I do not want nil to propagate the calling hierarchy. My initial idea is to throw an exception when self is nil, make a restore point, and abort.

Best ideas?

+4
source share
4 answers

The NSObject implementation [super init]will never return zero. The underlying implementation simply returns self .

, , nil, - . , -initWithContentsOfURL:error: URL. , , error:, . , , NSObject, .

. , . NSSetUncaughtExceptionHandler, , , . .

objective-c nil , ? . , nil, , , .

, initalizer . , .

:

NSError *error;
FooClass *myFoo = [[FooClass alloc] initWithContentsOfURL:blah error:&error]
if (myFoo == nil) {
  // ...
} else {
  // ...
}

, , . , error:, .

+8

: -

, , nil, NO, NULL - - . , , . NSError, . NSError , ( Mach, POSIX OSStatus) . (nil, NO ..) ; , NSError .

+4

, , nil .

[super init] nil (.. ), - , , , - .

nil , , , , , .

, , , , , .

" " , , .

+4

, "[super init]" , 20 - ( iOS), "nil" .

"nil" , nil, .

nil , , , ( ).

In Apple's โ€œConcepts in C Lens,โ€ they suggest, โ€œWhen you create an object, you should usually check if the return value is nil before continuing:โ€.

+2
source

All Articles