-3

Say I have some function that has to perform some asynchronous operation; the sequence is like this:

-(void) f1 {
    //1. invoke some asynchronous operation 

    //2. wait until asynchronous operation ends and invokes some delegate method 

    //3. let delegate method end

    //4. exit function
}

The function is called using GCD queue (serial or concurrent).

Constraints: notifications cannot be used; steps must be strictly in that order; NSOperation should not be used;

How the blocking part (#2 in the sequence) can be implemented?

BorisV
  • 683
  • 3
  • 20
  • 1
    If I understand your question right, you might want to look into using an `NSConditionLock`. This stack overflow answer has an example of a class that uses a `NSCondidtionLock`. https://stackoverflow.com/a/13372932/4102523 – tww0003 Apr 12 '19 at 19:18

1 Answers1

1

You could probably use GCD Semaphores:

@interface MyClass
@property (strong) dispatch_semaphore_t semaphore;
@end

@implementation MyClass

- (instancetype)init
{
    self = [super init];
    if (self) {
        _sempahore = dispatch_semaphore_create(0);
    }
    return self;

}

- (void)blockingMethod
{
    // let's assume someThing somehow already exists :)
    someThing.delegate = self;
    [someThing doAsyncStuff]; // will call someThingDelegateCallback when done

    dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
}

- (void)someThingDelegateCallback
{
    dispatch_semaphore_signal(self.semaphore);
}

@end
puzzle
  • 6,071
  • 1
  • 25
  • 30
  • 1
    @Boris You really don't want to do this kind of thing on the main thread. In fact, you really don't want to do this sort of async-to-sync kind of thing at all, unless it really can't be avoided. – bbum Apr 12 '19 at 19:45
  • 1
    I would advise listening to @bbum :) My answer probably does what you described, but it's very likely you shouldn't do it. – puzzle Apr 12 '19 at 20:25