Challenges

Anonymous block

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:

/​/​ ​O​p​t​i​o​n​ ​1​:​ ​T​o​t​a​l​l​y​ ​b​r​e​a​k​ ​i​t​ ​d​o​w​n​
i​n​t​ ​i​;​
i​ ​=​ ​5​;​
N​S​N​u​m​b​e​r​ ​*​n​u​m​ ​=​ ​[​N​S​N​u​m​b​e​r​ ​n​u​m​b​e​r​W​i​t​h​I​n​t​:​i​]​;​

/​/​ ​O​p​t​i​o​n​ ​2​:​ ​S​k​i​p​ ​t​h​e​ ​v​a​r​i​a​b​l​e​ ​d​e​c​l​a​r​a​t​i​o​n​
N​S​N​u​m​b​e​r​ ​*​n​u​m​ ​=​ ​[​N​S​N​u​m​b​e​r​ ​n​u​m​b​e​r​W​i​t​h​I​n​t​:​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.

NSNotificationCenter

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset