2014-07-23 42 views
0

我爲我的API使用塊,API類通過下面的代碼塊引發錯誤。我該如何重構錯誤的重複代碼?

[HJHLifeAPI deletePlantWithIdentifier:identifier completionHandler:^(NSError *error) { 
    if (error) { 
     [[error alertView] show]; 
     return ; 
    } 

    [self refresh:self.refreshControl]; 
}]; 

但問題是,我在幾個地方使用這種模式的代碼。因此,我應該寫幾個重複的代碼來處理錯誤。有什麼方法可以重構這段代碼嗎?我認爲例外可以是一個解決方案,但我認爲蘋果不鼓勵開發者使用它。

回答

0

這取決於您的HJHLifeAPI是如何設計的。

我通常使用AFNetworking API的東西,這裏是一個例子。

// This is the method like deletePlantWithIdentifier: 
// It actually invoke __requestWitPath: 
- (void)requestSomethingWithId:(NSString *)memId done:(NetDoneBlock)done 
{ 
    NSMutableDictionary *param_ = @{@"key":@"id"}; 
    [self __requestWithPath:@"/apiPath.jsp" parameter:param_ done:done]; 
} 


#pragma PRIVATE 
- (void)__requestWithPath:(NSString *)apiPath parameter:(NSDictionary *)parameter done:(NetDoneBlock)done 
{ 
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:SERVER_URL]]; 

    AFHTTPRequestOperation *operation = [manager POST:apiPath parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
     } success:^(AFHTTPRequestOperation *operation, id responseObject) { 
      done(); 
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
      // Error Handle Here 
    }]; 

    [operation start]; 
} 

您可以在一個__request...中處理所有錯誤。

0

創建塊

void(^errorHandler)(NSError *error) = ^(NSError *error) { 
    if (error) { 
     [[error alertView] show]; 
     return ; 
    } 

    [self refresh:self.refreshControl]; 
} 

保存到某個地方(不要忘記copy it

self.errorHandler = errorHandler; 

到處重用:

[HJHLifeAPI deletePlantWithIdentifier:identifier completionHandler:self.errorHandler];