在 Objective-C 中,我为什么要检查 self = [super init] 是否不为零? [英] In Objective-C why should I check if self = [super init] is not nil?

查看:371
本文介绍了在 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.

这篇关于在 Objective-C 中,我为什么要检查 self = [super init] 是否不为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆