Search code examples
iosobjective-cblock

How to access an object which has been assigned inside a block?


I want to assign a value to two strings and then use them outside the block or maybe as a property in another class. But i get Null in return.

this is the code:

__block NSString* citySTR = nil;
__block NSString* countrySTR = nil;

[geocoder reverseGeocodeLocation:locationManager.location completionHandler:
 ^(NSArray* placemarks, NSError* error){
     if ([placemarks count] > 0)
     {
         citySTR = [[placemarks objectAtIndex:0] administrativeArea];
         countrySTR = [[placemarks objectAtIndex:0] country];
     }
 }];

When i NSLog citySTR and countrySTR outside the block i get Null.


Solution

  • What do you want to do with the values afterwards? If you want to set a label or call an other class method you can do it inside the block. Another solution is to do delegation / add observer:

     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingHappens:) name:@"notificationName" object:nil]; - this one suppose to listen do the event (called at the initialisation)
    

    and this one invoking it:

     [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:obj];
    

    You can have citySTR and countrySTR as properties - maybe that can help