ios - 从 setCompletionBlockWithSuccess block 中获取值(value)

标签 ios afhttprequestoperation

我想从 Web 服务中获取一些数据并且它工作正常但是现在我想存储 block 中变量的返回值,但是变量的值仅在 block 内更改并且它返回 null 在 block 外,我该怎么做?这是我的代码:

-(void)getDataFromServer:(NSString *) urlString{
__block id returnedData;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

NSURLCredential *credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceNone];

NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:@"GET" URLString:urlString parameters:nil];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCredential:credential];
[operation setResponseSerializer:[AFJSONResponseSerializer alloc]];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
   // NSLog(@"Success: %@", responseObject);
    returnedData = responseObject;
    NSLog(@"returned data%@" , returnedData); // here returnedData contains the value that I need to store

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Failure: %@", error);
} ];

[manager.operationQueue addOperation:operation];
NSLog(@"returned data%@" , returnedData); // here it returns null value !! 
}

最佳答案

问题不在于访问变量,而在于时间。

您的第二个 NSLog 语句在运行完成 block 之前运行。该操作异步运行,并且您在 returnedData 被设置到完成 block 之前记录它。

编辑以添加示例解决方案:

一种解决方案是在您的调用类中创建完成 block 并传递到 getDataFromServer: 方法中的操作。

- (void)getDataFromServer:(NSString *)urlString completion:(void (^)(AFHTTPRequestOperation *operation, id responseObject))completion {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    NSURLCredential *credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceNone];

    NSMutableURLRequest *request = [manager.requestSerializer requestWithMethod:@"GET" URLString:urlString parameters:nil];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCredential:credential];
    [operation setResponseSerializer:[AFJSONResponseSerializer alloc]];
    [operation setCompletionBlockWithSuccess:completion];

    [manager.operationQueue addOperation:operation];
}

关于ios - 从 setCompletionBlockWithSuccess block 中获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29125259/

相关文章:

ios - post方法如何只发送必需的参数objective-c

objective-c - iOS- AFNETWORKING 2.0 -AFHTTPRequestOperationManager - 后多部分请求

ios - 自定义 UILabel 不显示文本

ios - iOS 应用程序的分数跟踪系统中的变量未更新

iphone - 在 iPhone 通讯录中使用查找电话号码时意外崩溃

ios - 当我为 AFNetworking 设置我的 downloadProgressBlock 时,它只会在最后调用一次

ios - 如何处理 AFHTTPRequestOperation 中的空 responseObject

android - 在小部件树 Flutter 中检测到重复的 GlobalKey

iOS 通用应用程序 - 自定义 UITableViewCell

iOS:管理一个 AFHTTPRequestOperationManager