DrFloyd5
DrFloyd5

Reputation: 13787

Should I retain a object pointer parameter in every method?

I am trying to get the hang of retain / release. I get that they are a matched set. But I don't know when I have to retain references.

-(void)sampleMethod:(RandomClass *) obj {
    [obj  retain];
    // Do stuff to object...
    [obj release];
}

Is it necessary to retain (and thus release) obj?

I am worried about obj going away. Does it follow that you must (if) retain reference parameters as soon as possible in the function? What about the space of time between the functions call and the first instruction of the function?

Thanks!

Upvotes: 3

Views: 1290

Answers (2)

bbum
bbum

Reputation: 162712

Short answer; use ARC.

Joe's answer is more or less correct. Until it isn't.

In general, there is no need to retain arguments or return values from other methods. However, the resulting code only works by coincidence and convention, not by algorithmic analysis.

Consider:

NSString *foo = [aMutableArray objectAtIndex: 5];
[aMutableArray removeObjectAtindex: 5];
[someTextField setTextValue: foo];

BOOM!

Your code just crashed. Maybe (it won't crash if foo happens to be a constant string or happens to have been retained by something else or happens to have been retain/autoreleased somewhere else).

Technically, that should be:

NSString *foo = [aMutableArray objectAtIndex: 5];
[foo retain];
[aMutableArray removeObjectAtindex: 5];
[someTextField setTextValue: foo];
[foo release];

That is, foo should be retained the moment it comes into scope and released the moment it is no longer used in a scope. Or you could [[foo retain] autorelease];, but autorelease pressure can be a problem (it generally isn't, but it can be).

ARC does this kind of analysis and would ensure that foo is retained as shown above when necessary.

Upvotes: 5

Joe
Joe

Reputation: 57179

You do not have to worry about the object being passed going away so there is no need to retain it. Proper memory management* ensures that the object will live for the duration of your method because it will be within the same thread as the caller, therefore the autorelease pool for that thread should not be drained and the caller can not release the object until your method has returned. This even holds true with methods such as performSelectorInBackground because that will retain the argument.

*Proper memory management - This means each thread that uses auto released objects gets it own autorelease pool that is drained within the same context it is created and objects passed across threads are properly retained.

Upvotes: 5

Related Questions