Wow. This answer is correct, but it is too reworked. Just use @synchronized() .
foo.h:
@interface Foo { id expensiveResult; } - (void) bar; @end
Foo.m:
@implementation Foo - (void) bar { @synchronized(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 in all instances, create a global variable in +(void)initialize - NSString will do everything right - and @synchronized() .
However, your question raises a much more important question. In particular, there is never a case when the same method will be called twice at the same time, unless you explicitly set up the application for this to happen.
The answer provided the sound more as a fix for the symptom than a fix for the real problem.
Note. It relies on an expensiveResult zero, which will be the same as all iVars when instantiating. Obviously, the reset value of ivar is zero if you want to recount.
source share