本文介绍了在Objective C代码中返回init中的nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,如果我们在init方法中返回nil,那么保留计数发生了什么以及谁将要释放这个对象?

In the case, if we return nil in the init method, what's happening with retain count and who is going to release this object?

我尽快承诺当我们调用alloc(将在init之前发生)时,保留计数将变为1.现在,init被调用,并且由于某种原因让它说不能初始化对象,所以它返回nil。

As I undertand as soon as we called alloc (which will happen before init), the retain count will become 1. Now, init is called and let say for some reason it can't initialize the object, so it returns nil.

现在我们看到保留计数等于1的对象,没有人引用它来调用release。

And it looks like now we have the object with retain count equal 1 and nobody has reference to it to call release.

我们应该打电话这种情况下init的[self autorelease]或做其他事情?

Should we call [self autorelease] in init for such case or do something else?

推荐答案

参见。

具体来说,如果初始化程序中有错误,那么 release self 并返回 nil

Specifically, if you have an error in your initializer, then you release self and return nil:

- init
{
    self = [super init];
    if (self) {
         if (... failed to initialize something in self ...) {
             [self release];
             return nil;
         }
    }
    return self;
}

现在,考虑一下当你打电话给 [super]时会发生什么init] 并返回 nil 。上面的模式已经被使用, self 已经被释放,而 nil 返回表明实例是不见了。没有泄漏,每个人都很高兴。

Now, consider what happens when you call [super init] and it returns nil. The above pattern has already been employed, what was self has been released, and the nil return indicates that the instance is gone. There is no leak and everyone is happy.

这也是一个有效的模式(假设 self 是一个实例 MyClass ):

This is also a valid pattern (assume that self is an instance of MyClass):

- init
{
    self = [super init];
    if (self) {
        ... normal initialization here ...
    } else {
        self = [MyClass genericInstanceWhenInitializationGoesBad];
        self = [self retain];
    }
    return self;
 }

由于 init 是期望返回保留的内容(暗示从 + alloc 链接),然后 [self retain] 虽然看起来很傻,但实际上是正确的。 self = [self retain] 只是在防范 MyClass 覆盖 retain 做一些奇怪的事情。

Since init is expected to return something that is retained (by implication of being chained from +alloc), then that [self retain], though it looks goofy, is actually correct. The self = [self retain] is just being extra defensive in case MyClass overrides retain to do something weird.

这篇关于在Objective C代码中返回init中的nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 06:03