问题描述
我有一个关于在 Objective-C 中编写 init 方法的一般问题.
I have a general question about writing init methods in Objective-C.
我到处都看到(Apple 的代码、书籍、开源代码等),在继续初始化之前,init 方法应该检查 self = [super init] 是否为 nil.
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] 是否为 nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!