ObjectiveC块和变量 [英] ObjectiveC Blocks and Variables
问题描述
我有以下方法可以通过我的iOS应用(使用Restkit)进行网络服务调用...
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;
但是,我在valid
变量上遇到错误,说它在块外声明并且不能分配.我在Google上搜索了一下,发现一条建议,我这样宣告有效...
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;
摆脱了错误.但是,我发现无论我在块内将valid
值设置为什么,退出该块时都无法正确设置该值.如何设置此值,以便我的方法返回期望值?
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?
推荐答案
我认为您不了解块是如何工作的.尽管__block
是正确的,但这不是可变可见性的问题.
I think you don't understand how blocks work. It's not a matter of variable visibility, although __block
is correct.
您的代码块是一个异步执行的函数,因此,只要执行该代码块,valid
就会设置为resp.value
,这很可能会在您的return语句之后发生.
You block is a function executed asynchronously, so valid
will be set to resp.value
whenever 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.
编辑
示例
- (void)didFinishValidation:(BOOL)valid {
// Do whatever you like with the `valid` value
if (valid) {
//...
} else {
//...
}
}
您的方块变成
[objectManager getObjectsAtPath:servicePath parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
BooleanServiceResponse *resp = [mappingResult firstObject];
valid = resp.value;
[self didFinishValidation:valid];
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(@"Error while validating session for user %@ : %@", username, error);
}];
这篇关于ObjectiveC块和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!