如果[super init]返回nil怎么办? [英] What to do if [super init] returns nil?

查看:91
本文介绍了如果[super init]返回nil怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下面的代码为例

- (id)init {
    self = [super init];
    if (self) {
        // code
    }
    return self;
}

我不希望nil向上传播到调用层次结构.我最初的想法是在self为nil的情况下引发异常,创建一个还原点并中止执行.

I do not want nil to propagate up the calling hierarchy. My initial idea is to throw an exception in case self is nil, make a restore point and abort execution.

更好的主意?

推荐答案

NSObject的[super init]实现将永远不会返回nil. 基本实现只是返回self .

NSObject's implementation of [super init] will never return nil. The base implementation just returns self.

通常,初始化程序返回nil的唯一原因是是否发生非致命错误.例如,您可能调用了-initWithContentsOfURL:error:并传递了无效的URL.按照惯例,可能会以这种方式失败的方法具有error:参数,该参数包含有关失败的信息.大多数初始化程序都不可能产生可恢复的错误,因此像NSObject一样,它们永远不会返回nil.

In general, the only reason that an initializer returns nil is if a nonfatal error occurred. For example, you might have called -initWithContentsOfURL:error: and passed an invalid URL. By convention, methods that may fail in this way have an error: parameter, which contains information about the failure. Most initializers do not have the possibility of a recoverable error, so like NSObject, they will never return nil.

致命错误通常会引发异常或中止程序.因此,检查nil对他们没有帮助.处理致命错误的最佳选择是

Fatal errors typically throw an exception or abort the program. So checking for nil is no help with them. Your best bet to handle fatal errors is NSSetUncaughtExceptionHandler, although you should be aware that saving data is risky in the case of a fatal error, as the unsaved data may be corrupted. Don't overwrite good data in that case.

即使超类永远不会返回nil,为什么Objective-C代码总是在初始化程序中检查nil?公约,大部分.可以说,通过始终检查nil,对于超类而言,将来在无需更改子类的情况下添加失败条件变得更加容易,但这实际上只是一个约定.

Why does objective-c code always check for nil in initializers, even when super will never return nil? Convention, mostly. Arguably, by always checking for nil, it becomes easier for a superclass to add a failure condition in the future without requiring subclasses to be changed, but really it's just a convention.

最后,在超级类初始化程序中,初始化器不是检查失败的正确位置.如果可能出现可恢复的错误,则调用方应检查该错误.

Finally, the initalizer is not the right place to check for failure in a superclass initializer. If recoverable errors are a possibility, the caller should check for the error.

示例:

NSError *error;
FooClass *myFoo = [[FooClass alloc] initWithContentsOfURL:blah error:&error]
if (myFoo == nil) {
  // ...
} else {
  // ...
}

每次初始化对象时检查nil都是过大的.仅当存在error:参数或该方法具有已记录的可恢复错误时,才需要执行此操作.

Checking for nil whenever you initialize an object is overkill. This only needs to be done when there is an error: argument, or the method has a documented recoverable error.

这篇关于如果[super init]返回nil怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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