自动释放用法的澄清

发布于 2024-12-10 18:25:27 字数 582 浏览 0 评论 0原文

在我使用 autorelease 发送的大多数代码中,对象最终从函数返回。显然,在此之后不能调用release,而 autorelease 是正确的方法。但是,在对象要传递给另一个将保留它的对象的情况下,使用 autorelease 是否同样有效?

例如,

-(void)foo
{
   SomeClass *someObject = [[[SomeClass alloc] init] autorelease];
   //Do some things
   self.someOtherClass.someProperty = someObject;
}

在将对象分配给 someProperty 后释放该对象是否有任何实际差异:

-(void)foo
{
   SomeClass *someObject = [[SomeClass alloc] init]];
   //Do some things
   self.someOtherClass.someProperty = someObject;
   [someObject release];
}

是否存在后者比前者更可取的情况?

In most of the code that I've sen using autorelease, the object is ultimately returned from the function.Clearly release cannot be called after this point and autorelease is the way to go. However in situations where the object is going to passed to another object that will retain it is using autorelease just as valid?

For example

-(void)foo
{
   SomeClass *someObject = [[[SomeClass alloc] init] autorelease];
   //Do some things
   self.someOtherClass.someProperty = someObject;
}

Is there any practical difference to releasing the object after it is assigned to someProperty:

-(void)foo
{
   SomeClass *someObject = [[SomeClass alloc] init]];
   //Do some things
   self.someOtherClass.someProperty = someObject;
   [someObject release];
}

Are there any situations where the later is more preferable to the former?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

裂开嘴轻声笑有多痛 2024-12-17 18:25:27

两者都是可以接受的,但建议您使用发布版本以避免 内存峰值还有其他问题

在这里释放是可以接受的,因为您可以假设对象的接收者将保留它,如果稍后需要的话。因此,您可以在收到后立即安全地释放。

Both are acceptable, but you are accouraged to use the release version to avoid memory spikes an other problems.

It's acceptable to release here because you can assume that the receiver of the object will retain it, if it needs if later. So you can safely release as soon as it's given.

冷弦 2024-12-17 18:25:27

我认为后者在内存使用和 CPU 使用方面总是会表现得稍好一些,但每次分配只会好一点。

如果您不想编写三行代码并且没有性能问题,请随意使用前者。请注意,前者实际上可以用一条语句编写,根本不需要局部变量。

I think the latter will always perform slightly better in terms of memory usage and CPU usage, but only by a tiny amount per allocation.

Feel free to use the former if you prefer not to write three lines of code and are not having a performance problem. Note that the former can actually be written in one statement without a local variable at all.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文