Blocks are an extension of the C language and are fully supported by Objective-C, the underlying programming language for all things Mac. In the new iOS 4, blocks are used more and more instead of (or to replace)
Delegates and delegate methods
Callback functions
Completion handlers for one-time operations
Other enumeration techniques
Asynchronous tasks that need performed
With iOS 4, the following methods and functions of the system frameworks take blocks as parameters:
Completion handlers
Notif handlers
Enumeration
View animation and transitions
Sorting
Blocks can be declared as variables, but you can also write a block literal inline where it's required as an argument.
To declare a block variable:
Use the ^ operator with the name of the variable.
For example, to declare a block variable that returns void and takes an NSNotification * as its single argument, do the following:
void (^keyBoardWillShow) (NSNotification *)
Just as with any other variable declaration (such as int i = 1), follow the equals sign with its definition.
You do that by using the ^ operator again to indicate the beginning of the block literal — the definition assigned to the block variable. The block literal includes argument names as well as the body (or code) of the block. For example, to inform the compiler that the name of the argument is notif, do the following
= ^(NSNotification * notif) { code
And then end the block literal with the usual
};
Use the block variable, as you would any other variable, as an argument in a message:
usingBlock:keyBoardWillShow
To write a block literal inline, use the ^ operator to indicate the beginning of the block literal — the definition assigned to the block variable. The block literal includes argument names as well as the body (code) of the block.
For example, to write a block literal inline where it's required as an argument for usingBlock, do the following:
usingBlock:^(NSNotification * notif) { code
And then end the block literal with the usual (no semicolon is needed because it is being used as an argument within a message)
}
dummies
Source:http://www.dummies.com/how-to/content/using-block-objects-in-iphone-and-ipad-game-develo.html
No comments:
Post a Comment