Why not throw an exception if [super init] returns nil?

后端 未结 4 2415
北海茫月
北海茫月 2021-02-19 18:15

This is considered typical

- (id)init {
    self = [super init];
    if (self) {
        // <#initializations#>
    }
    return self;
}

4条回答
  •  耶瑟儿~
    2021-02-19 18:54

    Returning nil is the appropriate thing to do. Part of the reason that sending any message to nil is allowed and defined to return nil as a result is that you can build compound statements like:

    resultObject = [[[[class alloc] init] autorelease] someProperty];
    

    That statement executes all the way through even if any individual method call returns nil. To fit with that, the init convention is to return the nil if the superclass does so.

    As JustSid points out, ObjC uses exceptions only for unrecoverable problems.

提交回复
热议问题