1

I'm new to using blocks, and they really seem like a great alternative to delegate methods. I implemented a simple block to do some simple math after watching a few tutorials, but I'm really struggling in being able to get them to do much more than that thanks to their wacky syntax.

Could someone help explain how I'd implement a block in objective-c that would do something similar to the pseudo code below?

  1. Call block from within a method
  2. The block looks at a class array and notifies the caller if it is populated (has a count of > 0)
  3. If the array's count is 0, the block will notify the caller when it has something added to it and the block will then stop

Thanks!

William LeGate
  • 540
  • 7
  • 18
  • 1
    I'd be much more inclined to use something other than blocks. http://stackoverflow.com/questions/15612553/how-to-add-observer-on-nsmutablearray – Paul Dardeau Jan 17 '14 at 20:05

1 Answers1

4

You're imputing too much power and flexibility to Blocks. They're just functions. They get called, they run, they return a value.

The only difference between a Block and a plain function that does the same work is that a Block can be treated as an object for purposes of being put into collections like arrays. They're easier to use for things like delegation because they can be defined in a scope other than file-level, and they'll capture variables from that scope. The Block syntax is so confusing because it's based on function pointers, famously the most gnarly part of C syntax.

There's no "Block notifies caller" functionality inherent to Blocks. You can only pass a return value back.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • +1 But, blocks also automatically capture local scope which is an advantage they have over regular functions. – Andrew Madsen Jan 17 '14 at 20:18
  • +1 to Josh's comments, with one qualifier. An interesting feature of blocks is that they inherit the variables from their enclosing scope, even though they can persist after program execution leaves that scope. – Duncan C Jan 17 '14 at 20:18