
[英]AFNetworking: enqueueBatchOfHTTPRequestOperations issue with completion block
[英]AFNetworking block variable update issue
我正在使用AFNetworking从服务器接收回JSON,并且使用此JSON确定我的Objective-C函数的返回值。 不管JSON是什么,d的值都不会在初始化时改变(作为假值)。 为什么会这样呢? 我的代码如下:
-(BOOL)someFunction{
__block BOOL d;
d = FALSE;
//the value of d is no longer changed
operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *req, NSHTTPURLResponse *response, id jsonObject) {
if(![[jsonObject allKeys] containsObject:@"someString"]){
d = TRUE;
}
else {
d = FALSE;
}
}
failure:^(NSURLRequest *req, NSHTTPURLResponse *response, NSError *error, id jsonObject) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Alert"
message: @"Could not connect to server!"
delegate: nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
d = FALSE;
}];
[operation start];
return d;
}
您应该将异步函数与返回成功BOOL的完成块一起使用。
- (void)myBeautifulFunction
{
[self someFunctionWithCompletion:^(BOOL success) {
if (!success) {
[self showAlert];
}
}];
}
- (void)someFunctionWithCompletion:(void (^)(BOOL success))completion
{
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *req, NSHTTPURLResponse *response, id jsonObject) {
if (![[jsonObject allKeys] containsObject:@"someString"]){
if (completion) {
completion(YES);
}
} else {
if (completion) {
completion(NO);
}
}
} failure:^(NSURLRequest *req, NSHTTPURLResponse *response, NSError *error, id jsonObject) {
if (completion) {
completion(NO);
}
}];
[operation start];
}
该操作将异步执行,但您将同步返回d
的值。 您应该从操作完成块中触发任何需要d值的东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.