内存管理和 viewDidLoad(iphone、objective-c)

发布于 2024-09-13 06:40:33 字数 165 浏览 3 评论 0原文

我在 viewDidLoad 中分配一个 NSArray (首先这样做可以吗,就像这是一个好的做法吗?)但是我在哪里释放它呢?在ViewDidUnload、dealloc或didRecieveMemoryWarning中?

(我还应该向它发送消息以释放,或将其设置为 nil,或清空数组或组合吗?)

I am allocating an NSArray in viewDidLoad (firstly is that alright to do, like is it good pratice?) but where do I release it? In ViewDidUnload, dealloc or didRecieveMemoryWarning?

(also should I message it to release, or set it to nil, or empty the array or a combination?)

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

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

发布评论

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

评论(3

云裳 2024-09-20 06:40:33

您应该将 NSArray 分配给 self 的保留属性,并在 viewDidLoad 中(自动)释放它。然后在dealloc中释放它。在此设置中,当 viewDidLoad 被调用时,它会释放“当前”NSArray(如果有)。

但如果可能的话,听起来您最好在 init 函数之一中分配 NSArray。

You should assign the NSArray to a retained property of self, and (auto)release it in viewDidLoad. Then release it in dealloc. In this setup, when viewDidLoad gets called it releases the "current" NSArray, if any.

But it sounds like you'd better alloc the NSArray in one of the init functions, if possible.

终难遇 2024-09-20 06:40:33

您可以在 viewDidLoad 中进行分配,当每个项目被释放时,它将调用release(当您添加它们时,它会调用retain,因此请确保在需要时释放)。

如果你不需要它,你应该尽快释放它。如果您想保留它(因为它是缓存),那么您可以在所有三种情况下释放它,但不要多次释放它。

You can allocate in viewDidLoad, and it will call release on each item when it is dealloced (it calls retain when you add them, so make sure you release if you need to).

If you don't need it around, you should release it as soon as possible. If you want to hold onto it (because it's a cache), then you can release in all three cases, but don't release it more than once.

只为守护你 2024-09-20 06:40:33

要释放对象,请发送释放消息:

[myObject release];

请参阅 dealloc 中的属性:release 然后设置为 nil?或者直接发布以获取更多详细信息。

没有必要清空数组。当数组上的引用计数降至零时,它将对其所有对象调用[对象释放]。

To release an object, send a release message:

[myObject release];

See Properties in dealloc: release then set to nil? or simply release for more details.

It's not necessary to empty the array. When the reference count on the array drops to zero, it will call [object release] on all of its objects.

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