I have several ViewControllers ,and a "networkClient" subclass of NSObject which offer functions of get/post data.
if "networkClient" occur an error when get/post data,the functions will return an error info for the ViewControllers who call get/post functions.
I found I always have lots of same code in different ViewControllers, such as:
- (void)showAlertWithString:(NSString *)string{
SIAlertView *alertView = [[SIAlertView alloc]initWithTitle:@"Error" andMessage:string];
[alertView addButtonWithTitle:@"OK"
type:SIAlertViewButtonTypeDestructive handler:^(SIAlertView *alertView){
}];
[alertView show];
}
since I don't want to include the 3rd party library "SIAlertView" and write the code -(void)showAlertViewWithString in every ViewControllers.
I'm wondering is there a way to include the library and write the code only in "networkClient" and return this -(void)showAlertViewWithString to the ViewControllers and let them execute it in the ViewControllers when the error happened?
update: thanks for the answers, as I'm a beginner of iOS development I just know there's a method called 'block' and after I tried, it seemed work.
below is the code which I tried to use block instead delegate to call "show alert" in ViewControllers.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"action" : @"create_user",
@"email" : email,
@"password" :password,
@"user_name" :name,
@"mobile": number
};
[manager POST:kLoginURL
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
SIAlertView *alertView = [[SIAlertView alloc]initWithTitle:@"Alert" andMessage:@"Success"];
[alertView addButtonWithTitle:@"ok" type:SIAlertViewButtonTypeDestructive handler:^(SIAlertView *alertView){
}];
[alertView show];
}
// [self.delegate createAccountResult:(responseObject)];
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}