One situation where I found blocks useful is if I want a method to return multiple values:
Method Definition Method UsageSome pitfalls can be found immediately, though:
1. You have to handle some contextual issues, such as the need to declare some __block variables so as to fetch the return values from within the result block.
2. Calls to such methods can not be chained or embedded in compound expressions (as can methods returning a single value):
Another Method Definition Another Method UsageOne might argue that by wrapping the return values in collection objects(array, dictionary) we can as well achieve the same effect. That's true, but not so elegant as blocks. Suppose we'd used array to implement the function for finding out the max & min elements in an array of integers. We would have had to establish some kind of contract between the function and it's caller------with what indices can the caller extract max & min respectively------and yet with which there was no mechanism to prevent the caller from running beyond the bounds for the returned array. With dictionary we also have the similar issue------to prevent misspelling the key used to extract max & min, we would have had to define some NSString* const & make them accessible beyond the scope where the function was declared in the first place, which, was not so clean. The ability of blocks to allow defining "structures" on the fly enables us to write code that's far more elegant & cleaner than can be done with any other techniques(in Objective-C).
PS:
1. For the sake of concentration, just don't bother with the potential safety issues resulted from the integers parameter and just focus on the concepts & ideas expressed by the example.
2. If you'd ever used the far more expressive Swift language, you'd found this idea'd been built into the language as a powerful feature, which was called tuple.
网友评论