niR
niR

Reputation: 1

__block variable returns nil on method call

I have a method which has block string variable which is passed to retrieve API data inside block function. However it returns nil. On debugging the addressPlace has nil value.

 - (NSString *)getAddressForPlaceAPI:(double)latitudePassed longitude:(double)longitudePassed
 {
    __block NSString * addressPlace = nil;
    NSString *url = @"";
    url = [NSString stringWithFormat:@"%@lat=%@&lng=%@",kGeoCodeURL, [NSString    stringWithFormat:@"%f",latitudePassed],[NSString stringWithFormat:@"%f", longitudePassed]];
   [WebServiceObj callWebServiceGET_withAPIName:url withParam:nil withCompletion:^(BOOL isSuceess, NSDictionary *response)
   {
         if(isSuceess)
         {
                 addressPlace = [[response valueForKey:KEY_RESULTS][0] valueForKey:KEY_FORMATTEDADDRESS];
                 NSLog(@"ADDRESSPP*** = %@",addressPlace);

         }
         else
         {
             NSLog(@"FAIL API = %s","FAIL");
         }
 }];
return addressPlace;
 }

Any idea on why this may be happening? Thanks in advance.

Upvotes: 0

Views: 202

Answers (1)

Apurv
Apurv

Reputation: 17186

The reason is method callWebServiceGET_withAPIName works in an asynchronous way. So before it returns into completion handler, your code will reach at the end of the function like and returns addressPlace as nil.

To solve that, you should also pass a block in the argument of the method getAddressForPlaceAPI. So whenever your success block executes once callWebServiceGET_withAPIName returns the value, you can throw the value back to your parent block.

Upvotes: 1

Related Questions