0

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

-(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 !! 
}
4

1 回答 1

1

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

您的第二NSLog条语句在完成块运行之前运行。该操作异步运行,并且您returnedData在完成块中设置它之前进行记录。

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

一种解决方案是在调用类中创建完成块,然后进入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];
}
于 2015-03-18T14:57:05.743 回答