views:

116

answers:

2

I don't mean to start a code formatting holy war here, but I'm wondering if anyone has any advice on how to best format nested blocks in Objective-C.

Here's some code I wrote today:

 [UIView animateWithDuration:1.0
      animations:^{
       self.alpha = 0.5;
      }
      completion:^(BOOL finished){
       [UIView animateWithDuration:1.0
            animations:^{
             winView.alpha = 1.0;             
            }
            completion:^(BOOL finished){
             winView.alpha = 0.0;
            }];
  }];

I pretty much let XCode format it, and it's not terrible. But I'm kinda afraid in six months I'll stumble across this to fix some bug, and want to punch myself in the face.

Anyone have any pointers on how to make nested blocks as readable as possible?

+3  A: 

And that is exactly why the common standard is to have only one block parameter to a method or function and always have the block as the last one. In this case, this was likely the most natural thing for UIView to offer and there you have it.

In any case, your approach is the right one. If anything, I might break out the inner block as a local variable and pass it as an argument. Or maybe more of the blocks.

However, the approach of being able to select an entire file and have Xcode reformat the whole thing is a tremendous time saver; I do select-all-tab on my source all the time. Minimizes diffs and inconsistencies.

bbum
+1  A: 

The real issue here is methods that take multiple block arguments, which make it either ugly or hard to read. I haven't written any real code that needs to use it yet, but one possibility is to separate the } and ]; like this:

[UIView animateWithDuration:1.0
    animations:^{
        self.alpha = 0.5;
    }
    completion:^(BOOL finished){
        [UIView animateWithDuration:1.0
            animations:^{
                winView.alpha = 1.0;             
            }
            completion:^(BOOL finished){
                winView.alpha = 0.0;
            }
        ];
    }
];

This breaks the standard formatting of blocks (which keeps } and ]; together), but I think it is slightly more readable.

Nick Forge
Yah -- that works, too. And still allows for select-all-format in Xcode...
bbum
Yes, I like that, thanks!
zpasternack