tyler
tyler

Reputation: 424

Objective-C get variable out of block

I'm struggling with getting a variable out of a block. Seems to be a pretty basic thing but I can't figure it out! How can I access it? e.g. usercity out of the block? Usercity is declared as NSString in .h.

[ceo reverseGeocodeLocation: loc completionHandler:
 ^(NSArray *placemarks, NSError *error) {


     CLPlacemark *placemark = [placemarks objectAtIndex:0];
     //NSLog(@"placemark %@",placemark);
     //String to hold address
     //NSString *locatedAt = [[placemark.addressDictionary valueForKey:@"FormattedAddressLines"] componentsJoinedByString:@", "];
     //NSLog(@"addressDictionary %@", placemark.addressDictionary);

     //NSLog(@"placemark %@",placemark.region);
     NSLog(@"Land %@",placemark.country);  // Give Country Name
     NSLog(@"City %@",placemark.locality); // Extract the city name
     NSLog(@"Adresse %@",placemark.name);
     //NSLog(@"location %@",placemark.ocean);
     NSLog(@"Zip %@",placemark.postalCode); //ZipCode
     NSLog(@"sonstiges %@",placemark.subLocality);


     //Save values in variables
     usercountry = placemark.country;
     usercity = placemark.locality;
     userzip = placemark.postalCode;
     NSLog(@"usercity: %@",usercity);

     //NSLog(@"location %@",placemark.location);



 }

 ];

Upvotes: 0

Views: 986

Answers (2)

hlfcoding
hlfcoding

Reputation: 2542

Is this what you're looking for?

__block NSString *userCity;
[ceo reverseGeocodeLocation: loc completionHandler:^(NSArray *placemarks, NSError *error) {

     CLPlacemark *placemark = [placemarks objectAtIndex:0];
     ...
     userCity = placemark.locality;

}];

But if you want to actually be able to check its value outside of the block, you'll have to do so after the completion handler updates the value. Perhaps make it a property, ie. self.userCity?

Upvotes: 1

gnasher729
gnasher729

Reputation: 52530

Your code in the block has to store usercity where you want it. You can't "get something out" of a block, the code in the block has to do it.

You do know that a block can access all variables in the surrounding method, don't you?

Upvotes: 0

Related Questions