The example in this chapter puts the block declaration, assignment, and usage on three separate lines of code for readability.
When you need to pass an integer into a method, such as NSNumber’s numberWithInt:, you can pass the int anonymously:
// Option 1: Totally break it down int i; i = 5; NSNumber *num = [NSNumber numberWithInt:i]; // Option 2: Skip the variable declaration NSNumber *num = [NSNumber numberWithInt:5];
Because blocks are variables, you can do this with blocks as well. In fact, this is the most common way to use blocks. You will rarely declare a block variable so that you can pass the block into methods; you’ll usually use them anonymously.
Modify the exercise in this chapter to pass the block anonymously as an argument to enumerateObjectsUsingBlock:. That is, keep the block, but get rid of the block variable.
In Chapter 24, you used NSNotificationCenter’s addObserver:selector:name:object: method to register to receive callbacks via your zoneChange: method. Update that exercise to use the addObserverForName:object:queue:usingBlock: method instead. Look up its details in the developer documentation.
This method takes a block as an argument and then executes the block instead of calling back to your object when the specified notification is posted. This means that your zoneChange: method will never be called. The code inside this method will instead be in the block.
The passed-in block should take a single argument (an NSNotification *) and return nothing, just as the zoneChange: method does.
You can pass nil as the argument for queue:; this argument is used for concurrency, a topic we won’t cover in this book.