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!