Objective-C 中何时发布的参考

发布于 2024-09-12 05:35:24 字数 270 浏览 12 评论 0原文

我在 Objective-C 中经常遇到一个问题。我要么发布太多次,要么发布不够。或者也许我没有足够地保留它们......

有人可以给我指出一个很好的参考资料,它可以为我提供何时需要保留和释放的经验法则吗?

例如:

我记得在某处读到有些对象是预先保留的,所以我需要释放它们,但不保留它们。这些是什么物体?

如果我分配一个对象并且只在该方法中需要它,我是否需要释放它?保留它吗?

显然,如果我保留了某些东西,我需要释放它,但除此之外,我会有点迷失。

I'm having a recurring problem in Objective-C. I'm either releasing things too many time, or not enough. or perhaps I'm not retaining them enough...

Can someone point me at a good reference that will give me a rule of thumb on when I need to retain and release?

For example:

I remember reading somewhere that some objects come pre-retained, so I need to release them, but not retain them. Which objects are these?

if I alloc an object and only need it in that method, do I need to release it? retain it?

Obviously, if I retained something, I needtorelease it, but beyond that, I get a bit lost.

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

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

发布评论

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

评论(2

心凉 2024-09-19 05:35:24

规则通常非常简单。如果您通过以下方式之一获取对象:

id obj = [[MyObject alloc] init];
id obj = [myObject retain];
id obj = [myObject copy];
id obj = [myObject mutableCopy];

那么您需要在某个时刻释放它——通常使用相同的方法或您的dealloc方法。换句话说,使用匹配的 平衡对 allocretaincopymutableCopy 的调用释放 调用。

我记得在某处读到过一些对象是预先保留的,所以我需要释放它们,但不保留它们。这些是什么物体?

这种情况很少发生。被调用方法的文档应指定您负责释放返回的对象;否则,您应该假设您正在接收一个自动释放的对象。

如果我分配了一个对象并且只在该方法中需要它,我需要释放它吗?保留它吗?

是的,您需要释放它(但不需要保留它)。 (如果您只想在该方法中使用它,您还可以使用返回自动释放对象的便捷方法之一。)

The rules are generally pretty simple. If you get an object in one of the following ways:

id obj = [[MyObject alloc] init];
id obj = [myObject retain];
id obj = [myObject copy];
id obj = [myObject mutableCopy];

then you need to release it at some point -- in the same method, or your dealloc method, generally. In other words, balance your calls to alloc, retain, copy, and mutableCopy with a matching release call.

I remember reading somewhere that some objects come pre-retained, so I need to release them, but not retain them. Which objects are these?

This happens rarely. The documentation for the called method should specify that you are responsible for releasing the returned object; otherwise, you should assume you're receiving an autoreleased object.

if I alloc an object and only need it in that method, do I need to release it? retain it?

Yes, you need to release it (but you don't need to retain it). (You can also use one of the convenience methods that return an autoreleased object if you're only going to use it in that method.)

策马西风 2024-09-19 05:35:24

有一个且只有一个规范参考:Apple 的 内存管理Cocoa 或 iPhone 指南

There is one and only one canonical reference: Apple's Memory Management Guide for Cocoa or iPhone.

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