内存管理和 viewDidLoad(iphone、objective-c)
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该将 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 indealloc
. 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.您可以在 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.
要释放对象,请发送释放消息:
请参阅 dealloc 中的属性:release 然后设置为 nil?或者直接发布以获取更多详细信息。
没有必要清空数组。当数组上的引用计数降至零时,它将对其所有对象调用[对象释放]。
To release an object, send a release message:
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.