tags:

views:

427

answers:

1

Consider the following ObjC code example:

-(void) doStuffWithString: (String *) 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: (String *) someParam {
    [stringParam retain];
    // Do stuff with someParam
    [stringParam release];
}
+6  A: 

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.

Andrew Grant