Skip to content

Instantly share code, notes, and snippets.

@simonwhitaker
Last active August 29, 2015 13:57
Show Gist options
  • Save simonwhitaker/9557073 to your computer and use it in GitHub Desktop.
Save simonwhitaker/9557073 to your computer and use it in GitHub Desktop.
Wrapping a method implementation

Here's a nice trick for wrapping a method's implementation in a block, for example for logging the return value.

Have you ever written a method with a load of conditionals and return statements...

- (int)statusCode {
    if (foo) {
        return 1;
    }
    if (bar) {
        return 2;
    }
    return 0;
}

...and then found yourself wanting to log that return value?

You might have ended up re-writing the method like this:

- (int)statusCode {
    int result;
    if (foo) {
        result = 1;
    } else if (bar) {
        result = 2;
    } else {
        result = 0;
    }
    NSLog(@"Result: %i", result);
    return result;
}

But that seems so, well, inelegant, doesn't it?

Here's a more refined way – wrap the method body in an anonymous block, call it and capture the result:

- (int)statusCode {
    int result = ^int{
        if (foo) {
            return 1;
        }
        if (bar) {
            return 2;
        }
        return 0;
    }(); # Note the () to call the block
    NSLog(@"Result: %i", result);
    return result;
}

That makes for a pretty low-footprint diff:

diff -w original.m amended.m
1a2
>     int result = ^int{
8a10,12
>     }(); # Note the () to call the block
>     NSLog(@"Result: %i", result);
>     return result;

Nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment