I have the following method that makes a webservice call from my iOS app (using Restkit)…
BOOL valid = NO;
RKObjectManager *objectManager = [RKObjectManager sharedManager];
NSString *servicePath = [WebServiceHelper pathForServiceOperation:[NSString stringWithFormat:@"/security/isSessionValid/%@", username]];
[objectManager getObjectsAtPath:servicePath parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
BooleanServiceResponse *resp = [mappingResult firstObject];
valid = resp.value;
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(@"Error while validating session for user %@ : %@", username, error);
}];
return valid;
However, I get an error on the valid variable, saying it is declared outside the block and is not assignable. I Googled around a bit, and found a recommendation that I declare valid like this instead…
__block BOOL valid = NO;
That gets rid of the error. However, I find that no matter what I set the valid value to within my block, it is not set appropriately when exiting the block. How can I set this value so my method returns the expected value?
I think you don’t understand how blocks work. It’s not a matter of variable visibility, although
__blockis correct.You block is a function executed asynchronously, so
validwill be set toresp.valuewhenever that block is executed, which is very likely to happen later than your return statement.You need to change your design since so far you are returning an object which is not guaranteed to be set.
EDIT
Example
and your blocks become