【问题标题】:Returning nil in the init in Objective C code在 Objective C 代码的 init 中返回 nil
【发布时间】:2010-12-02 15:58:13
【问题描述】:

在这种情况下,如果我们在 init 方法中返回 nil,retain count 会发生什么,谁将释放这个对象?

正如我所理解的,一旦我们调用 alloc(这将在 init 之前发生),保留计数将变为 1。现在,调用 init 并假设由于某种原因它无法初始化对象,所以它返回 nil .

现在看起来我们有一个保留计数等于 1 的对象,并且没有人引用它来调用释放。

对于这种情况,我们应该在 init 中调用 [self autorelease] 还是做其他事情?

【问题讨论】:

标签: iphone objective-c


【解决方案1】:

请参阅文档中的Allocating and Initializing Objects

具体来说,如果您的初始化程序中有错误,那么您 release self 并返回 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 返回表示实例已经消失。没有泄漏,每个人都很高兴。

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

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

由于init 预计会返回retained(暗示从+alloc 链接),那么[self retain] 尽管看起来很傻,实际上是正确的。 self = [self retain] 只是为了防止MyClass 覆盖retain 做一些奇怪的事情而采取额外的防御措施。

【讨论】:

【解决方案2】:

通常,你会调用

self = [super init];
if (self == nil) {

   return nil;
}
// do some init job here
return self;

自动释放 self 不是你的工作,因为当你拥有它时,它已经是 nil,所以即使你调用[self autorelease];,它也什么都不做。

我认为 NSObject 的 init 方法已经处理了对象

【讨论】:

  • 为什么不if(self) { // do some init job here } return self
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多