You can use dispatch_semaphore_t
for that purpose.
So dispatch_semaphore_wait
will wait until dispatch_semaphore_signal
will be triggered.
Here is a Basic implementation which will block your main thread if you will use it like that
@interface ViewController ()
@property (nonatomic) dispatch_semaphore_t semaphore;
@end
@implementation ViewController
- (float)calculateDistance{
self.semaphore = dispatch_semaphore_create(0);
[SocketNetwork requestDistance:(point *A, point *B)];
//here: how to wait util self.distance has a value -> we return / if not, we still wait.
dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
return self.distance;
}
//socketNetwork delegate
- (void)receivedResponseFromServer:responseDistance{
self.distance = responseDistance;
dispatch_semaphore_signal(semaphore);
}
Here is nice implementation that I advice you to use (using blocks)
typedef void (^DistanceCalculationCallback) (float distance);
@interface ViewController ()
@property (copy, nonatomic) DistanceCalculationCallback distanceCallback;
@end
@implementation ViewController
//--------------------------------------------//
#pragma mark - Public Methods
//--------------------------------------------//
- (void)calculateDistanceWithCompletion:(DistanceCalculationCallback)aCallback
{
self.distanceCallback = aCallback;
[SocketNetwork requestDistance:(point *A, point *B)];
}
//--------------------------------------------//
#pragma mark - SocketNetwork delegate
//--------------------------------------------//
- (void)receivedResponseFromServer:(float)responseDistance
{
if (self.distanceCallback) {
self.distanceCallback(responseDistance);
}
}
//--------------------------------------------//
#pragma mark - LifeCycle
//--------------------------------------------//
- (void)viewDidLoad
{
[super viewDidLoad];
// We will load distance here for exampple
[self calculateDistanceWithCompletion:^(float distance) {
NSLog(@"Distance is %f", distance);
}];
}