Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to retain/release method parameters in Objective-C?

Tags:

objective-c

Consider the following ObjC code example:

- (void)doStuffWithString:(NSString *)someParam {
    // Do stuff with someParam
}

If this code were being executed in a multi-threaded app, would it be a good idea to retain/release someParam? Specifically, I'm thinking of scenarios in which the passed-in parameter is a singleton object shared by many threads. Is the following safer, for example?

- (void)doStuffWithString:(NSString *)someParam {
    [stringParam retain];
    // Do stuff with someParam
    [stringParam release];
}
like image 553
Clint Harris Avatar asked Feb 17 '09 00:02

Clint Harris


People also ask

When should you retain release?

The basic premise behind the system is that if you want to hold on to a reference to another object, you need to issue a retain on that object. When you no longer have a use for it, you release it.

How do you declare a method in Objective C?

An Objective-C method declaration includes the parameters as part of its name, using colons, like this: - (void)someMethodWithValue:(SomeType)value; As with the return type, the parameter type is specified in parentheses, just like a standard C type-cast.


1 Answers

No, it's not the job of individual functions to try and provide thread-safety for parameters.

Somewhere up the stack something passed down the object that is the parameter to "doStuffWithString". This is the code that should guarantee the that object will remain valid through the length of the function call.

Two things to consider;

  1. In situations where you call a third-party or library function these will not do a retain/release for you.
  2. If there is a danger of the param being deleted this could occur before your call to 'retain' even happens!

This thread may also be helpful.

like image 114
Andrew Grant Avatar answered Oct 21 '22 12:10

Andrew Grant