EdBer EdBer - 2 months ago 11
Objective-C Question

UIAlertController as a Utility that accepts function parameter

I have this UIAlertController as a utility that accepts two paremeters, the title and the content. I want to modify the "confirm" button. I want to duplicate this utility and add another parameter the will execute a specific function.

-(UIAlertController *) modalWithTitle : (NSString *) title andContent: (NSString *) content{

UIAlertController *alert = [UIAlertController alertControllerWithTitle: title message:content preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){}];

[alert addAction:defaultAction];
return alert;
}


Example code :

UIAlertController *alert =[[ModalController alloc] modalWithTitle:@"Error" andContent:@"Network unavailable."
andAction:<ENTER FUNCTION TO EXECUTE HERE>];
[self presentViewController:alert animated:YES completion:nil];

Answer

You can write it like this:

+ (UIAlertController *)modalWithTitle:(NSString *)title andContent:(NSString *)content andHandler:(void (^)(UIAlertAction *))handler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle: title message:content preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:handler];
    [alert addAction:defaultAction];
    return alert;
}

Usage:

void (^handler)(UIAlertAction *) = ^(UIAlertAction *action) {
    // code to execute
};
[[ModalController alloc] modalWithTitle:@"title" andContent:@"content" andHandler:handler];

Another approach:

+ (UIAlertController *)modalWithTitle:(NSString *)title andContent:(NSString *)content andHandler:(void (^)(void))handler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:content preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        handler();
    }];
    [alert addAction:defaultAction];
    return alert;
}

Usage:

void (^block)(void) = ^{
    // code to execute
};
[[ModalController alloc] modalWithTitle:@"title" andContent:@"content" andHandler:block];