views:

41

answers:

3

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

A: 

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.

Lou Franco
A: 

To release an object, send a release message:

[myObject release];

See http://stackoverflow.com/questions/3402234/properties-in-dealloc-release-then-set-to-nil-or-simply-release/3402247#3402247 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.

Seamus Campbell
I know how to release an object. I'm asking where.
Jonathan
I was responding to the second part of our question, about what the right way to release an object is ([obj release], self.obj = nil, ...). mvds has accurately answered the first part.
Seamus Campbell
+1  A: 

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.

mvds
But if I autorelease it and release it in dealloc, won't that release it twice? And cause an error because it's trying to release an object that doesn't exist.
Jonathan
Yes, but you want it released twice: the first time because you get it with a retain count of one from the start, and the second time because your object hangs on to it because you assigned it to a retained property. I.e. by doing `self.prop = [obj autorelease]` you effectively transfer ownership from the function to the object.
mvds