In Objective-C why should I check if self = [super init] is not nil?(在 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] 是否不为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Objective-C 中,我为什么要检查 self = [super init] 是否不为零?


基础教程推荐
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01