使用NSXPCConnection

时间:2016-02-10 00:49:35

标签: objective-c multithreading cocoa xpc nsxpcconnection

我正在使用NSXPCConnection,我的一个接口调用有一个回复块,如下所示:

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

我称之为:

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

我的理解是,回复块是异步运行的,并且可能在方法返回后运行。

我想同步测试返回代码,最好的方法是什么?

进一步澄清上面的代码段:proxy对象是使用NSXPCConnection方法从remoteObjectProxy对象获取的远程对象。这是一个重要的细节,因为这会影响调用回复块的队列。

4 个答案:

答案 0 :(得分:3)

这就是派遣小组的目的。

NSTimeInterval timeout = 120; // in seconds
__block NSInteger status;

dispatch_group_t syncGroup = dispatch_group_create();
dispatch_group_enter(syncGroup);

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

dispatch_time_t waitTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(NSEC_PER_SEC * timeout));

if(dispatch_group_wait(syncGroup, waitTime) != 0)
{
    // complain about a request timing out
}

// enjoy your status

如果您选择使用remoteObjectProxyWithErrorHandler来获取代理,那么您需要记住在错误处理程序中调用dispatch_group_leave(syncGroup)。

答案 1 :(得分:3)

我刚刚发现了一种更好的方法:

在创建远程对象时,使用synchronousRemoteObjectProxyWithErrorHandler代替remoteObjectProxy

不需要信号灯或组。

答案 2 :(得分:2)

  

我想同步测试返回码,最好的方法是什么   做到了吗?

你真的不希望它同步运行。这只会阻止运行该块的队列/线程,并且通常会造成严重破坏。

相反,在status = rc;行之后,调用可以处理完成事实的事情。让方法返回,让队列或事件循环运行,然后在addItem:withLabel:完成时完成所需的工作。

像这样:

__block NSInteger status;
[proxy addItem:data withLabel:@"label" reply:^(NSInteger rc) {
             status = rc;
             // like this ...
             [someObject processReturnedStatus];
         }
];

答案 3 :(得分:0)

我建议使用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;