我使用的是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对象是使用remoteObjectProxy方法从NSXPCConnection对象获得的远程对象。这是一个重要的细节,因为这会影响调用应答块的队列。
发布于 2016-03-06 13:52:40
我建议使用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;发布于 2018-08-24 23:41:59
我刚找到了一种更好的方法
在创建远程对象时使用synchronousRemoteObjectProxyWithErrorHandler而不是remoteObjectProxy。
不需要信号量或信号组。
发布于 2016-03-05 00:21:48
这就是派遣小组的目的。
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)。
https://stackoverflow.com/questions/35305003
复制相似问题