2014-07-23 46 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];