Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 29 / 68

Higher-order functions (passing a block as an argument)

This lesson covers passing a block as an argument in Objective-C, with the aim of treating the work itself as a component.

Being able to pass a piece of work — a block — into another function is what makes it a higher-order function. Picture specifying only how the work should be done and leaving the doing to someone else. Passing a comparison rule to sortedArrayUsingComparator: is the classic example.

The sample code sorts into descending order by passing the ordering criterion as a block, as in sortedArrayUsingComparator:^NSComparisonResult(NSNumber *a, NSNumber *b) {...}. Starting with ^ is what marks Objective-C's block syntax.

A common early stumble is simply getting used to that notation. Until ^returnType(argType argName) {body} feels natural, the difference from an ordinary method definition is confusing.

In professional work, blocks are an important feature used all over iOS development, notably for completion callbacks on asynchronous work.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Objective-C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)