Objective-C: Blocks as A Way to Return Multiple Values from Methods

One situation where I found blocks useful is if I want a method to return multiple values:

Method Definition
Method Usage

Some 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 Usage


One 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.

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容