返回函数中的已分配内存的Objective-C ==不好吗? [英] Objective-C returning alloc'd memory in a function == bad?

查看:60
本文介绍了返回函数中的已分配内存的Objective-C ==不好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在iPhone上.

This is on the iPhone.

那如果我有像这样的功能呢?

So what if I have a function like

- (SomeObject*)buildObject;

我是否需要传递一个已经在外部分配的变量,如

Do I need to pass in a variable that I have already alloc'd outside like

- (void)assignObject(SomeObject** out);

或者我可以

- (SomeObject*)buildObject
{
   return [[[SomeObject alloc] init] autorelease];
}

并像使用它

SomeObject* obj = [[otherObject buildObject] retain];

我想做最后一个,但是据我所知,这是未定义的,因为自动释放只能保证对象直到函数结束?

I would like to do the last one, but as far as I've read this is undefined because autorelease only guarantees the object until the end of the function?

推荐答案

在Objective-C中,内存管理协定如下:调用alloc的人负责调用release.如果构造函数调用[[[Class alloc] init] release],则该对象将快速创建并销毁.

In Objective-C, the memory management contract goes as follows: whoever calls alloc is responsible for calling release. If the constructing function calls [[[Class alloc] init] release] then the object is quickly created and destroyed.

要解决此问题,构造函数将需要使用自动释放,如下所示:

To get around this, the constructing function would need to use autorelease as follows:

return [[[Class alloc] init] autorelease];

这会注册要在当前运行循环结束时释放的对象,除非有保留的对象,例如构造函数的调用者.就您而言,第二个示例正是您想要做的.

That registers the object to be released at the end of the current run loop unless something retains it, such as the caller of the constructing function. In your case, the second example is exactly what you want to do.

所以:

- (SomeClass*) buildObject {
   return [[[SomeClass alloc] init] autorelease];
}

- (void) doSomething {
   c = [self buildObject];
   // Call [c retain] if you want c to stay around after the current run
   // loop is finished and clean it up later, e.g. in your delloc method.
}

这篇关于返回函数中的已分配内存的Objective-C ==不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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