在Objective-C中,为什么要检查self = [super init]是否不为零?

在Objective-C中,为什么要检查self = [super init]是否不为零?

问题描述:

对于在Objective-C中编写init方法,我有一个普遍的疑问.

I have a general question about writing init methods in Objective-C.

我到处都看到(Apple的代码,书籍,开放源代码等),init方法应该在继续进行初始化之前检查self = [super init]是否不为零.

I see it everywhere (Apple's code, books, open source code, etc.) that an init method should check if self = [super init] is not nil before continuing with initialisation.

init方法的默认Apple模板为:

The default Apple template for an init method is:

- (id) init
{
    self = [super init];

    if (self != nil)
    {
        // your code here
    }

    return self;
}

为什么?

我的意思是init什么时候会返回nil?如果我在NSObject上调用init并返回nil,那么一定要搞砸了,对吧?在这种情况下,您甚至不编写程序...

I mean when is init ever going to return nil? If I called init on NSObject and got nil back, then something must be really screwed, right? And in that case, you might as well not even write a program...

类的init方法返回nil真的很常见吗?如果是这样,在什么情况下,为什么?

Is it really that common that a class' init method may return nil? If so, in what case, and why?

例如:

[[NSData alloc] initWithContentsOfFile:@"this/path/doesn't/exist/"];
[[NSImage alloc] initWithContentsOfFile:@"unsupportedFormat.sjt"];
[NSImage imageNamed:@"AnImageThatIsntInTheImageCache"];

...等等. (注意:如果文件不存在,NSData可能会引发异常).在很多地方,当出现问题时,返回nil是预期的行为,因此,出于一致性的考虑,通常几乎所有时间都检查nil是标准做法.

... and so on. (Note: NSData might throw an exception if the file doesn't exist). There are quite a few areas where returning nil is the expected behaviour when a problem occurs, and because of this it's standard practice to check for nil pretty much all the time, for consistency's sake.