Getting Started with Blocks(开始block)

The following sections help you to get started with blocks using practical examples.

接下来这一节有实用的例子帮你开始blocks.

Declaring and Using a Block (定义和使用block)

You use the ^ operator to declare a block variable and to indicate the beginning of a block literal. The body of the block itself is contained within {}, as shown in this example (as usual with C, ; indicates the end of the statement):

你使用^操作定义一个block值同时表示了一个block的开始。block的主题被{}包围,就像例子中展示的那样(就像通常的C中,分号;申明了一个语句的结束):

 int multiplier = ;
int (^myBlock)(int) = ^(int num) {
return num * multiplier;
};

The example is explained in the following illustration:

这个例子在下面的说面中得到了解释:

  • myBlock 的返回值是int类型的 。
  • 我们使用^声明了一个myBlock的block。
  • 只需要一个参数,也是int类型的。
  • 参数名是num。这是一个块的定义,
  • 给myblock赋值。
  • 这是block的主体。

Notice that the block is able to make use of variables from the same scope in which it was defined.

If you declare a block as a variable, you can then use it just as you would a function:

注意block可以使用定义在block定义作用用中的变量。

如果你把block定义成了一个变量,你可以像使用函数一样使用block。

 
 int multiplier = ;
int (^myBlock)(int) = ^(int num) {
return num * multiplier;
}; printf("%d", myBlock());
// prints "21"

Using a Block Directly(直接使用block)

In many cases, you don’t need to declare block variables; instead you simply write a block literal inline where it’s required as an argument. The following example uses the qsort_b function. qsort_b is similar to the standard qsort_r function, but takes a block as its final argument.

在很多情况下你不需要把block定义成一个变量;相反的你可以直接写出一个block作为参数。下面的例子用到了qsort_b函数,qsort_b很类似标准的qsort_r函数,是指使用一个block作为一最后一个参数。

 char *myCharacters[] = { "TomJohn", "George", "Charles Condomine" };

 qsort_b(myCharacters, , sizeof(char *), ^(const void *l, const void *r) {
char *left = *(char **)l;
char *right = *(char **)r;
return strncmp(left, right, );
}); // myCharacters is now { "Charles Condomine", "George", "TomJohn" }

Blocks with Cocoa(cocoa中的block)

Several methods in the Cocoa frameworks take a block as an argument, typically either to perform an operation on a collection of objects, or to use as a callback after an operation has finished. The following example shows how to use a block with the NSArray methodsortedArrayUsingComparator:. The method takes a single argument—the block. For illustration, in this case the block is defined as anNSComparator local variable:

Cocoa 框架中有一些方法使用block作为一个参数,特别是对多个对象进行操作,或者在一个操作结束之后回调。下面的例子展示了NSArray怎样在方法sortedArrayUsingComparator:中使用block。这个方法使用了一个参数——block。为了说明,这个block被定义为NSComparator类型的一个局部变量:

 NSArray *stringsArray = @[ @"string 1",
@"String 21",
@"string 12",
@"String 11",
@"String 02" ]; static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch |
NSWidthInsensitiveSearch | NSForcedOrderingSearch;
NSLocale *currentLocale = [NSLocale currentLocale]; NSComparator finderSortBlock = ^(id string1, id string2) { NSRange string1Range = NSMakeRange(, [string1 length]);
return [string1 compare:string2 options:comparisonOptions range:string1Range locale:currentLocale];
}; NSArray *finderSortArray = [stringsArray sortedArrayUsingComparator:finderSortBlock];
NSLog(@"finderSortArray: %@", finderSortArray); /*
Output:
finderSortArray: (
"string 1",
"String 02",
"String 11",
"string 12",
"String 21"
)
*/

__block Variables(_block 类型变量)

A powerful feature of blocks is that they can modify variables in the same lexical scope. You signal that a block can modify a variable using the__block storage type modifier. Adapting the example shown in Blocks with Cocoa, you could use a block variable to count how many strings are compared as equal as shown in the following example. For illustration, in this case the block is used directly and uses currentLocale as a read-only variable within the block:

block的另一个强大的特性是可以修改同一词法范围的变量。你可以把一个block想修改的变量声明成_block类型。改写Blocks with Cocoa中的例子,你可以在下面的例子中使用block变量统计有多少字符串是相同的。为了说明需要,例子中直接使用block,同时把currentLocate作为一个block中的只读变量。

 NSArray *stringsArray = @[ @"string 1",
@"String 21", // <-
@"string 12",
@"String 11",
@"Strîng 21", // <-
@"Striñg 21", // <-
@"String 02" ]; NSLocale *currentLocale = [NSLocale currentLocale];
__block NSUInteger orderedSameCount = ; NSArray *diacriticInsensitiveSortArray = [stringsArray sortedArrayUsingComparator:^(id string1, id string2) { NSRange string1Range = NSMakeRange(, [string1 length]);
NSComparisonResult comparisonResult = [string1 compare:string2 options:NSDiacriticInsensitiveSearch range:string1Range locale:currentLocale]; if (comparisonResult == NSOrderedSame) {
orderedSameCount++;
}
return comparisonResult;
}]; NSLog(@"diacriticInsensitiveSortArray: %@", diacriticInsensitiveSortArray);
NSLog(@"orderedSameCount: %d", orderedSameCount); /*
Output: diacriticInsensitiveSortArray: (
"String 02",
"string 1",
"String 11",
"string 12",
"String 21",
"Str\U00eeng 21",
"Stri\U00f1g 21"
)
orderedSameCount: 2
*/

This is discussed in greater detail in Blocks and Variables.

更详细的讨论请看:Blocks and Variables.

本文原创,转载请注明出处:http://blog.csdn.net/zhenggaoxing/article/details/44303047

最新文章

  1. easyUi load方法重新加载表单的数据
  2. python 在最后一行追加
  3. Office——EXCEL 显示 隐藏 Ribbon 调用宏
  4. HDU1024Max Sum Plus Plus(M段最大和)
  5. Handler Should be static or leaks Occur?
  6. splice()函数,&#39;SPLICE_F_MOVE&#39; &#39;SPLICE_F_NONBLOCK&#39; &#39;SPLICE_F_MORE&#39; undeclared
  7. java多线程:并发包中ReentrantReadWriteLock读写锁的原理
  8. opencv直方图均衡化
  9. lua定时器与定时任务的接口设计
  10. HDU 3436--Queue-jumpers (树状数组 or Splay Tree)
  11. IOS 动画的两种方式
  12. ionic/cordvoa 修改platform文件夹里的文件,build会覆盖问题
  13. Dapper中条件为In的写法
  14. 记一个在移动端调试 web 页面的方法
  15. jenkins疑惑
  16. μC/OS-II 创建一个任务的流程
  17. windows 中查找占用某个端口的进程并杀死的命令
  18. 自己写的browse.bat与perl写的url_handler.pl的比较
  19. CSS3美化有序列表
  20. SSM框架中将时间写入数据库的格式定义

热门文章

  1. 「网络流24题」「Codevs1237」 餐巾计划问题
  2. Healthy Holsteins
  3. linux部署web项目到tomcat下(图文详解)
  4. 6-6 Haar特征3
  5. Collection View Programming Guide for iOS---(一)----About iOS Collection Views
  6. 004--linux命令tar 软硬链接
  7. E20170503-hm
  8. sql server通过脚本进行数据库压缩全备份的方法
  9. bzoj 1090: [SCOI2003]字符串折叠【区间dp】
  10. 浅谈字符串哈希 By cellur925