Semaphores to run asynchronous method synchronously

夙愿已清 提交于 2019-12-23 05:05:13

问题


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.

This is my code:

-(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
        }
    }];

}

回答1:


Try this:

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


来源:https://stackoverflow.com/questions/34858307/semaphores-to-run-asynchronous-method-synchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!