NadavN7
NadavN7

Reputation: 367

Get data out of block iOS (Objective-C)

So,here a simple method with a block

    -(void)getPointsInRange:(double)radius nearByPoint:(SGPoint *)nearByPoint
{
    SGStorageQuery *query = [SGStorageQuery queryWithPoint:nearByPoint layer:SimpleGeoMainLayerName];

    [query setRadius:radius];
    [mainClient retain];
    [mainClient getRecordsForQuery:query
                      callback:[SGCallback callbackWithSuccessBlock:
                                ^(id response) {
                                    // you've got records!
                                    // to create an array of SGStoredRecord objects...

                                    NSArray *records = [NSArray arrayWithSGCollection:response  type:SGCollectionTypeRecords];
                                    NSLog(@"records received:%i",[records count]);

                                    [self arrayOfPointsReceived:records];
                                } failureBlock:^(NSError *error) {
                                    // handle failure
                                    NSLog(@"getPointsInRange error:%@",[error description]);
                                }]];


}

the method connects to some SDK and returns an NSArray with results. i want to find a way that the getPointsInRange method will return the NSArray. so its signature will be -(NSArray*)getPointsInRange... I can do it simply with delegate, but i'd like to do it all within one function.

Upvotes: 2

Views: 1251

Answers (1)

zoul
zoul

Reputation: 104065

It seems to me like you want to keep your cake and eat it, too. Or have a method that calls asynchronous code and at the same time returns the results synchronously. You can turn the method into a synchronous one, if that’s what you want:

- (void) computeSomethingAndReturnSynchronously
{
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    [self doSomeAsynchronousOperationWithCompletion:^{
        // take the call results here
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_release(semaphore);
}

This will run the asynchronous code and then block the execution until the results from the async call are available. Does that help? (I should add that I would much rather keep the code asynchronous and return the NSArray in another completion block.)

Upvotes: 2

Related Questions