2014-05-19 41 views
1

AFNetworking代碼有一些地方,其中__block用於沒有明顯需要更改對象的方法中的對象。例如,在AFHTTPSessionManager中,GET調用在任務對象上使用__block。任何想法爲什麼?在AFNetworking中,爲什麼有些返回對象聲明爲__block類型?

- (NSURLSessionDataTask *)GET:(NSString *)URLString 
        parameters:(NSDictionary *)parameters 
         success:(void (^)(NSURLSessionDataTask *task, id responseObject))success 
         failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure 
{ 
    NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters]; 

    __block NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { 
     if (error) { 
      if (failure) { 
       failure(task, error); 
      } 
     } else { 
      if (success) { 
       success(task, responseObject); 
      } 
     } 
    }]; 

    [task resume]; 

    return task; 
} 

同樣在其他類中,__block用於對象,如下面顯示的憑證對象。

- (void)URLSession:(NSURLSession *)session 
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge 
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler 
{ 
    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; 
    __block NSURLCredential *credential = nil; 

    if (self.sessionDidReceiveAuthenticationChallenge) { 
     disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential); 
    } else { 
     if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { 
      if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust]) { 
       credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; 
       if (credential) { 
        disposition = NSURLSessionAuthChallengeUseCredential; 
       } else { 
        disposition = NSURLSessionAuthChallengePerformDefaultHandling; 
       } 
      } else { 
       disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; 
      } 
     } else { 
      disposition = NSURLSessionAuthChallengePerformDefaultHandling; 
     } 
    } 

    if (completionHandler) { 
     completionHandler(disposition, credential); 
    } 
} 
+1

對我來說這看起來像一個錯誤。至少第一個是。 – CodaFi

回答

1

在這兩個地方,__block是無用的和不必要的。

在第一種情況下,變量task未在其定義的行上分配給初始化之後。 __block僅在變量被分配給(並且用於MRC中的非保留目的)時纔有用,因此這裏沒有意義。

在第二種情況下,變量credential根本不捕獲在塊中,因此它再次無用。

相關問題