Objective-C中的标准对象初始化不会导致内存泄漏吗? [英] Doesn't the standard object initialization in Objective-C lead to memory leaks?

查看:97
本文介绍了Objective-C中的标准对象初始化不会导致内存泄漏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中创建对象的标准方法如下:

The standard way to create an object in Objective-C looks like this:

MyClass* object = [[MyClass alloc] init];

MyClass init 方法的标准实现如下所示:

The standard implementation of MyClass's init method would look something like this:

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

除了一些语法更改之外,除了工厂方法之外,这似乎是编写和使用init方法的推荐方法.

Aside from some syntax changes, and excluding factory methods, that seems to be the recommended way to write an init method, and to use it.

据我了解, self = [super init]; 的目的是处理 [super init] 失败的情况.但是,如果确实失败并返回nil,会不会发生内存泄漏?原因是 MyClass 的init将返回nil, object 将为nil,将不再有引用用 [MyClass alloc]分配的对象的指针. ,因此无法释放它.

As I understand it, the purpose of self = [super init]; is to handle the case where [super init] fails. But if it does fail, and returns nil, wouldn't there be a memory leak? The reason being that MyClass's init will return nil, object will be nil, there will be no more pointers that reference the object allocated with [MyClass alloc], and therefore no way to release it.

这些是我能想到的两个解决方案,但是我在常规实践中都没有见过任何一个.

These are the two solutions I can think of are, but I haven't seen either one in regular practice.

在调用 alloc 之后,请在调用init之前检查结果:

After a call to alloc, check the results before calling init:

MyClass* object = [MyClass alloc];
if(object == nil) { /*handle the error */ }
else { object = [object init]; }

或者,如果 [super init] 失败,则释放内存.像这样:

Or, if [super init] fails, release the memory. Something like this:

-(id) init
{
    id temp = [super init];
    if(!temp) { [self release]; }
    self = temp;
    if(self) { /* initialize */ }
    return self;
}

我在这个推理上错了吗?可以说 [super init] 不太可能失败,但是为什么将其结果分配给 self 并检查nil?我很高兴看到一些澄清.

Am I wrong in that reasoning? It could be argued that [super init] is unlikely to fail, but then why assign the results of it to self and check for nil? I'd be happy to see some clarification.

推荐答案

如果[super init]要返回nil,它也应该自行调用release.

If [super init] wants to return nil, it should also call release on self.

这篇关于Objective-C中的标准对象初始化不会导致内存泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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