Is there an equivalent of the .NET ManualResetEvent class available for use in Objective-C / Cocoa?
4 Answers
I'm not very familiar with ManualResetEvent, but based on the documentation, it looks like the NSCondition class might be what you are looking for.
NSCondition is by no means an exact equivalent, but it does provide similar signaling functionality. You might also want to read up on NSLock.

- 9,213
- 3
- 38
- 43
-
1Reading up on the doc's this appears to do exactly what I needed. Thanks! – Lounges Jul 07 '09 at 23:19
-
It looks like NSCondition is more like AutoResetEvent and not ManualResetEvent. – Brett Jan 25 '13 at 03:50
-
Check out this useful sample:http://stackoverflow.com/questions/6158397/equivalent-of-gcd-serial-dispatch-queue-in-ios-3-x/6258379#6258379 – Brett Jan 25 '13 at 03:51
Here is a wrapper class I created which emulates ManualResetEvent using NSCondition.
@interface WaitEvent : NSObject {
NSCondition *_condition;
bool _signaled;
}
- (id)initSignaled:(BOOL)signaled;
- (void)waitForSignal;
- (void)signal;
@end
@implementation WaitEvent
- (id)initSignaled:(BOOL)signaled
{
if (self = ([super init])) {
_condition = [[NSCondition alloc] init];
_signaled = signaled;
}
return self;
}
- (void)waitForSignal
{
[_condition lock];
while (!_signaled) {
[_condition wait];
}
[_condition unlock];
}
- (void)signal
{
[_condition lock];
_signaled = YES;
[_condition signal];
[_condition unlock];
}
@end
I've done just some basic testing but I think it should get the job done with much less ceremony.

- 14,526
- 5
- 48
- 61
I'll give you the sample code I would have liked to find yesterday (but couldn't find anywhere). If you want to create a producer/consumer class where the consumer is asynchronous, this is what you need to do :
You need to declare and allocate the NSConditionLock.
NSArray * data = [self getSomeData];
if ( [data count] == 0 ) {
NSLog(@"sendThread: Waiting...");
[_conditionLock lockWhenCondition:1];
[_conditionLock unlockWithCondition:0];
NSLog(@"sendThread: Back to life...");
}
else {
// Processing
}
And in the main code, when you add data and you want to unlock the other thread, you just have to add :
[_conditionLock lock];
[_conditionLock unlockWithCondition:1];
Note: I don't describe here how data are exchanged between the producer and the consumer. In my program it was going through an SQLite/CoreData database, so thread sync is done at a higher level. But if you use a NSMutableDictionary, you need to add some NSLock.

- 11
- 1
Ah, those are poor man's condition variables.
You could use the NSCondition
class, but I think it's better
to go straight to the source. Start with pthread_cond_init
.
You gonna love it.

- 34,352
- 5
- 87
- 159
-
NSCondition is a higher-level wrapper around pthreads. If the NSCondition/NSLock interface does the job, there's no need to go low-level. – Naaff Jul 08 '09 at 01:21
-