objective-cmultithreadingcocoaxpcnsxpcconnection

How to synchronously wait for reply block when using NSXPCConnection


I'm using NSXPCConnection and one of my interface call has a reply block, like this:

- (void)addItem:(NSData *) withLabel:(NSString *) reply:(void (^)(NSInteger rc))reply;

Which I call like this:

__block NSInteger status;
[proxy addItem:data withLabel:@"label" reply:^(NSInteger rc)
         {
             status = rc;
         }
];

My understanding is that the reply block run asynchronously, and potentially after the method returns.

I want to test the return code synchronously, what's the best way to do it?


To clarify further the snippet above: the proxy object is the remote object obtained from an NSXPCConnection object using the remoteObjectProxy method. This is an important detail as this impact on which queue the reply block is invoked.


Solution

  • I propose to use dispatch_semaphore.

    // Create it before the block:
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block NSInteger status = 0;
    [proxy addItem:data withLabel:@"label" reply:^(NSInteger rc) {
                 status = rc;
                 // In the block you signal the semaphore:
                 dispatch_semaphore_signal(semaphore);
             }
    ];
    
    // here wait for signal
    // I dont remember exactly function prototype, but you should specify here semaphore and the time waiting (INFINITE)
    dispatch_semaphore_wait(...);
    
    // in non-ARC environment dont forget to release semaphore
    dispatch_release(semaphore);
    
    return status;