Both examples involve a callback. Your program sets up a situation where you'd like to defer the execution of some code to a later time. The classic example is a file dialog. You're asking the user for input, but don't necessarily halt the program until he makes up his mind. Another one is where you have a bunch of calculations that could be done concurrently. I still have to work up a good example of that.
Here we have a notification in the first example, and a timer in the second. The implementations use a category on NSObject. This works because a block is an Objective-C object. An alternative approach would be to use a function rather than a method.
The examples may look a bit strange. The block object is added as the observer, and its method
my_callBlockWithObject
or my_CallBlock
is called when the notification appears or the timer finishes. It looks strange because in the method, the block object is obtained with self and then called.Notice the use of
[block copy]
.// clang blocks.m -o prog -framework Foundation -fobjc-gc-only #import |
> ./prog2012-05-21 07:40:28.601 prog[3441:707] Note! |
// clang blocks.m -o prog -framework Foundation -fobjc-gc-only #import |
> ./prog 2012-05-21 07:41:00.457 prog[3455:707] Hello world! |