Tutorial :Memory Managment and viewDidLoad (iphone, objective-c)



Question:

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?)


Solution:1

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.


Solution:2

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.


Solution:3

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »