信号量以同步方式运行异步方法 [英] Semaphores to run asynchronous method synchronously

查看:138
本文介绍了信号量以同步方式运行异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我使用了异步类方法,该方法需要同步运行。

In my app, I use an asynchronous class method, that I need to run synchronously.

据我了解,我应该使用信号量来完成此操作。使用信号量是我以前从未做过的事情,所以现在我正在努力将它们放在正确的位置。

As far as I understand, I should use semaphores to accomplish this. Using semaphores is something I never had to do before, so now I'm struggling to put them in the right place.

我希望你们中的一些人可以在这里帮助我。

I hope some of you could help me out here.

这是我的代码:

-(void)CreateNewerEventInCalendar:(Event*)myEvent{
     [MyCalendar requestAccess:^(BOOL granted, NSError *error) {
                if (granted) {
            BOOL result = [MyCalendar addEventAt:myEvent.StartPoint withTitle:myEvent.Subject inLocation:myEvent.Location];
            if (result) {
                // added to calendar
            } else {
                // unable to create event/calendar
            }
        } else {
            // you don't have permissions to access calendars
        }
    }];

}


推荐答案

尝试一下:

dispatch_semaphore_t sema = dispatch_semaphore_create(0);

[MyCalendar requestAccess:^(BOOL granted, NSError *error) {

    // your implementation
    dispatch_semaphore_signal(sema);
}];

dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
// continue here

这篇关于信号量以同步方式运行异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆