我想从 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/