首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在使用NSXPCConnection时同步等待应答块

如何在使用NSXPCConnection时同步等待应答块
EN

Stack Overflow用户
提问于 2016-02-10 00:49:35
回答 4查看 3.4K关注 0票数 3

我使用的是NSXPCConnection,其中一个接口调用有一个应答块,如下所示:

代码语言:javascript
复制
- (void)addItem:(NSData *) withLabel:(NSString *) reply:(void (^)(NSInteger rc))reply;

我这样叫它:

代码语言:javascript
复制
__block NSInteger status;
[proxy addItem:data withLabel:@"label" reply:^(NSInteger rc)
         {
             status = rc;
         }
];

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

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

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

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-03-06 13:52:40

我建议使用dispatch_semaphore。

代码语言:javascript
复制
// 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;
票数 2
EN

Stack Overflow用户

发布于 2018-08-24 23:41:59

我刚找到了一种更好的方法

在创建远程对象时使用synchronousRemoteObjectProxyWithErrorHandler而不是remoteObjectProxy

不需要信号量或信号组。

票数 13
EN

Stack Overflow用户

发布于 2016-03-05 00:21:48

这就是派遣小组的目的。

代码语言:javascript
复制
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)。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35305003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档