Open Source: Objective-C Library That Dynamically Enables Block Based Calls – Like Magic!

Objective-C blocks are a topic that I’ve mentioned several times such as with the blocks cheat sheet for those new to using blcoks in Objective-C, and more recently some useful code that allows users to accurately time how long it takes to execute code within a block which is useful for code optimization.

I’ve also mentioned projects that offer a number of categories adding a block based syntax to many different classes such as BlocksKit.

Recently I came across a library known as A2DynamicDelegate that takes a different approach and automatically creates the necessary methods and properties enabling you to use block based calls to any delegate, datasource or other delegated protocol.

As the author Aleksander Anders states on the Github page:

There are many places in Objective-C where blocks make more sense than methods for delegation or simplistic function-like callbacks. While Apple is slowly migrating toward block callbacks (at the typically glacial pace of OS frameworks), A2DynamicDelegate serves to help bridge this gap by dynamically implementing protocol methods with blocks and creating block properties that do the same.

Here’s an example of A2DynamicDelegate in action:

(IBAction) annoyUser
{
    // Create an alert view
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle: @"Hello World!" message: @"This alert’s delegate is implemented using blocks. That’s so cool!" delegate: nil cancelButtonTitle: @"Meh." otherButtonTitles: @"Woo!", nil];

    // Get the dynamic delegate
    A2DynamicDelegate *dd = alertView.dynamicDelegate;

    // Implement -alertViewShouldEnableFirstOtherButton:
    [dd implementMethod: @selector(alertViewShouldEnableFirstOtherButton:) withBlock: ^(UIAlertView *alertView) {
        NSLog(@"Message: %@", alertView.message);
        return YES;
    }];

    // Implement -alertView:willDismissWithButtonIndex:
    [dd implementMethod: @selector(alertView:willDismissWithButtonIndex:) withBlock: ^(UIAlertView *alertView, NSInteger buttonIndex) {
        NSLog(@"You pushed button #%d (%@)", buttonIndex, [alertView buttonTitleAtIndex: buttonIndex]);
    }];

    // Set the delegate
    alertView.delegate = dd;

    [alertView show];
    [alertView release];
}

There is also a library included known as A2BlockDelegate that works with categories so you can extend an existing class, and dynamically add the block based syntax to the properties, and methods within your category.

Truly an amazing project that you really need to try yourself that you can find on Github here.

It’s no wonder why Alex called this his “Magnum Opus” on his twitter page.

©2012 iPhone, iOS 5, iPad SDK Development Tutorial and Programming Tips. All Rights Reserved.

.

DeliciousTwitterTechnoratiFacebookLinkedInEmail


Leave a Reply

Your email address will not be published. Required fields are marked *