0

在有人向我发送垃圾邮件告诉我它不是最佳实践之前,我有正当理由在这种情况下不使用异步方法。

我试图强制我的 AFNetworking 库以同步模式运行某些方法调用(它已被分解)。

这是我的(被黑)片段:

    NSURL *url = [NSURL URLWithString:_apiBaseUrl];
    AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:url];
    NSMutableURLRequest *request = [client requestWithMethod:@"POST" path:path parameters:nil];

    NSDictionary *requestDict = [NSDictionary dictionaryWithObjects:@[@"2.0", path, params, [NSNumber numberWithInt:(int)[[NSDate date] timeIntervalSince1970]]] forKeys:@[@"jsonrpc", @"method", @"params", @"id"]];

    NSString *requestBody = [requestDict JSONString];

    NSLog(@"requestBody: %@", requestBody);

    // Set the request body
    [request setHTTPBody:[requestBody dataUsingEncoding:NSASCIIStringEncoding]];
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

        // Do something with the success (never reached)
        successBlock(request, response, JSON);

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        failureBlock(request, response, error, JSON);
    }];

    if (queue == 1) {
        [self.operationArray addObject:operation];
    }
    else {
        [operation waitUntilFinished];
        successBlock(nil, nil, nil);            
        //[operation start];

    }

当运行该方法并且队列参数强制该方法 waitUntilFinished 时,永远不会到达成功块,也不会到达下一行。如果我使用 start 方法,它工作正常。

4

0 回答 0