Wow. That answer is correct, but way over-engineered. Just use @synchronize().
Foo.h:
@interface Foo
{
id expensiveResult;
}
- (void) bar;
@end
Foo.m:
@implementation Foo
- (void) bar
{
@synchronize(self) {
if (expensiveResult) return expensiveResult;
.... do expensive stuff here ....
expensiveResult = [theResult retain];
}
return expensiveResult;
}
@end
If you have multiple instances of Foo and want to guarantee exclusivity across all instances, create a global variable in +(void)initialize
-- an NSString will do fine -- and @synchronize()
on that.
However, your question raises a much more important question. In particular, there is never a case where the same method is going to be called twice simultaneously unless you quite explicitly configured your application to cause exactly that to happen.
The answer(s) provided sound more like a fix to a symptom and not a fix for the real problem.
Note: This is relying on expensiveResult being nil, which it will be as all iVars are nil on instantiation. Obviously, reset the ivar to nil if you want to recalculate.