Clicky

iOS Dev Nugget 95 Block-based API with BlocksKit

.

Need to run a code review on your codebase? Hire me

Blocks are a wonderful construct in ObjC and in certain cases, can help reduce boilerplate code. A good example is the BlocksKit library which adds block-based interfaces to Cocoa and Cocoa Touch classes.

Let's look at how you would normally use an UIAlertView. You show it by:

- (void)someFunc {
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Go", nil];
    //alertView.tag = SOME_TAG; //Probably set a tag value if you are showing more than one alert view if the UIAlertView delegate is responsible for more than one UIAlertView
    [alertView show];
}

And the delegate:

- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    //check alertView.tag if this delegate is responsible for more than one UIAlertView
    if (buttonIndex != alertView.cancelButtonIndex) {
        //Do something
    }
}

Note that the code will get messier if the delegate has to handle more than one UIAlertView.

With BlocksKit, you'd do:

- (void)someFunc {
    [UIAlertView showAlertViewWithTitle:@"Title" message:@"Message" cancelButtonTitle:@"Cancel" otherButtonTitles:@[@"Go"] handler:^(UIAlertView* alertView, NSInteger buttonIndex) {
        if (buttonIndex != alertView.cancelButtonIndex) {
            //Do something
        }
    }];
}

You don't have to implement the UIAlertViewDelegate and the handling code is localized to where the UIAlertView is shown.

BlocksKit contains lots of gems like this, such as NSDictionary+BlocksKit.h which adds Smalltalk-style selectors, such as -each:, -select:, -reject: to NSDictionary.

Check it out.


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues