问题
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