Using Blocks in iOS 4: The Basics(一)

2014-11-24 11:02:54 · 作者: · 浏览: 6

iOS 4 introduces one new feature that will fundamentally change the way you program ingeneral: blocks. Blocks are an extension to the C language and thus fully supported inObjective-C. If you're coming from a programming language such as Ruby, Python, or Lisp,then you know the power of blocks. Simply put, blocks let you encapsulate chunks of codeand pass them around like any other object. It's a different style of programming thatyou'll want to become familiar with to take advantage of new APIs in iOS 4.

Let's start by taking a look at two examples of where you might use blocks in iOS 4: view animations and enumeration.

Blocks By Example
As our first example, suppose we're creating a card game and we want to animate slidinga card from the dealer's hand to a player's position. Fortunately, the UIKit frameworkdoes all the heavy lifting when it comes to performing animations. What gets animated,however, is specific to your application. You specify what will be animated in a block,and toss it over to theanimateWithDuration:animations: method, like so:

[cpp]
[UIView animateWithDuration:2.0
animations:^ {
self.cardView.alpha = 1.0;
self.cardView.frame = CGRectMake(176.0, 258.0, 72.0, 96.0);
self.cardView.transform = CGAffineTransformMakeRotation(M_PI);
}
];
When this animation block is run, our card view will animate in three ways: change itsalpha to fade in the card, change its position to the lower-right of the frame (theplayer's position), and rotate itself 180 degrees (to give the dealer style points).

Our second example of blocks is to enumerate over a collection of cards and print the name and index of each card. You could use afor loop for this, but in iOS 4 the NSArray class has a handyenumerateObjectsUsingBlock: method that takes a block. Here's how to use it:

[cpp]
NSArray *cards =
[NSArrayarrayWithObjects:@"Jack", @"Queen", @"King", @"Ace", nil];

[cards enumerateObjectsUsingBlock:^(idobject, NSUIntegerindex, BOOL *stop) {
NSLog(@"%@ card at index %d", object, index);
}];
As we'll explore a bit more later, this block takes three parameters: the currentelement in the array, its index, and a flag to signal whether enumeration should stop(which we've ignored). TheenumerateObjectsUsingBlock: method calls theblock once for each element in the array and supplies the parameters.

So the upshot of using blocks in your Mac and iOS apps is that they allow you to attach arbitrary code to Apple-provided methods. Although similar in concept to delegation, passing short inline blocks of code to methods is often more convenient and elegant.

That's a good start, but it's important to understand what's going on. Whenever I'm learning anything new, I like to break it down into its simplest elements, get comfortable with how they work, and then (hopefully) put everything back together again. That way I feel confident with the code I write and can quickly debug any problems. So let's step back for a minute and learn how to declare and call basic blocks.

Block Basics
A block is simply a chunk of executable code. For example, here's a block that prints the current date and time:

[cpp]
^ {
NSDate*date = [NSDatedate];
NSLog(@"The date and time is %@", date);
};
The caret () introduces a block literal and the curly braces enclose statements that make up the body of the block. You can think of a block as being similar to an anonymous function.

So if it's anonymous, how exactly do we use this block The most common way to use ablock is to pass it to a me