views:

52

answers:

2

I'm writing an NSArray category to include the -objectAtRandom message that returns an object from a random index (something similar to Python's choice).

Should I autorelease this object before returning it? I believe I shouldn't, but I'm not sure...

+3  A: 

According to the normal memory management rules, no, you should not. Since you're presumably using objectAtIndex: to return the object, you don't need to do any memory mangement of your own.

Carl Norum
A: 

I'd write return [[object retain] autorelease] - this will guarantee, that even if array will be released, user will be able to work with object until current runloop cycle finish.

kovpas
This is not needed. The NSArray maintains a strong reference until it is removed from the array. If the developer deletes the array probably should understand that they are potentially releasing all of the objects that it contains.
AdamH
@AdamH, yeah, may be you are right.
kovpas
@adam So if the user want's to make sure he won't end with an invalid reference to the object, he should retain it and release it when done?
Fernando
Right. You can do whatever you want but once your code has released control you must retain the object if you want to use it later. If you're only using the object in a local scope you don't really need to retain it.
AdamH