博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
(译)IOS block编程指南 2 block开始
阅读量:5299 次
发布时间:2019-06-14

本文共 5352 字,大约阅读时间需要 17 分钟。

接下来这一节有实用的例子帮你开始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中,分号;申明了一个语句的结束):

1 int multiplier = 7;2 int (^myBlock)(int) = ^(int num) {3     return num * multiplier;4 };

 

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。

 
1 int multiplier = 7;2 int (^myBlock)(int) = ^(int num) {3     return num * multiplier;4 };5  6 printf("%d", myBlock(3));7 // 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作为一最后一个参数。

1 char *myCharacters[3] = { "TomJohn", "George", "Charles Condomine" };2  3 qsort_b(myCharacters, 3, sizeof(char *), ^(const void *l, const void *r) {4     char *left = *(char **)l;5     char *right = *(char **)r;6     return strncmp(left, right, 1);7 });8  9 // 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 method. The method takes a single argument—the block. For illustration, in this case the block is defined as an local variable:

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

1 NSArray *stringsArray = @[ @"string 1", 2                            @"String 21", 3                            @"string 12", 4                            @"String 11", 5                            @"String 02" ]; 6   7 static NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch | 8         NSWidthInsensitiveSearch | NSForcedOrderingSearch; 9 NSLocale *currentLocale = [NSLocale currentLocale];10  11 NSComparator finderSortBlock = ^(id string1, id string2) {12  13     NSRange string1Range = NSMakeRange(0, [string1 length]);14     return [string1 compare:string2 options:comparisonOptions range:string1Range locale:currentLocale];15 };16  17 NSArray *finderSortArray = [stringsArray sortedArrayUsingComparator:finderSortBlock];18 NSLog(@"finderSortArray: %@", finderSortArray);19  20 /*21 Output:22 finderSortArray: (23     "string 1",24     "String 02",25     "String 11",26     "string 12",27     "String 21"28 )29 */

 

__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 , 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类型。改写中的例子,你可以在下面的例子中使用block变量统计有多少字符串是相同的。为了说明需要,例子中直接使用block,同时把currentLocate作为一个block中的只读变量。

1 NSArray *stringsArray = @[ @"string 1", 2                           @"String 21", // <- 3                           @"string 12", 4                           @"String 11", 5                           @"Strîng 21", // <- 6                           @"Striñg 21", // <- 7                           @"String 02" ]; 8   9 NSLocale *currentLocale = [NSLocale currentLocale];10 __block NSUInteger orderedSameCount = 0;11  12 NSArray *diacriticInsensitiveSortArray = [stringsArray sortedArrayUsingComparator:^(id string1, id string2) {13  14     NSRange string1Range = NSMakeRange(0, [string1 length]);15     NSComparisonResult comparisonResult = [string1 compare:string2 options:NSDiacriticInsensitiveSearch range:string1Range locale:currentLocale];16  17     if (comparisonResult == NSOrderedSame) {18         orderedSameCount++;19     }20     return comparisonResult;21 }];22  23 NSLog(@"diacriticInsensitiveSortArray: %@", diacriticInsensitiveSortArray);24 NSLog(@"orderedSameCount: %d", orderedSameCount);25  26 /*27 Output:28  29 diacriticInsensitiveSortArray: (30     "String 02",31     "string 1",32     "String 11",33     "string 12",34     "String 21",35     "Str\U00eeng 21",36     "Stri\U00f1g 21"37 )38 orderedSameCount: 239 */

 

This is discussed in greater detail in .

更详细的讨论请看.

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

 

转载于:https://www.cnblogs.com/tenglong2500/p/4793766.html

你可能感兴趣的文章
登录界面
查看>>
1.7-BGP③
查看>>
第3章 ES文档和故障处理
查看>>
jquery实现返回基部案例效果
查看>>
oracle 电子商务解决方案讲义
查看>>
屏幕录制H.264视频,AAC音频,MP4复,LibRTMP现场活动
查看>>
padding与margin的差别
查看>>
RDD的依赖关系
查看>>
类型"Microsoft.Office.Interop.Word.ApplicationClass"未定义构造函数
查看>>
Android简易实战教程--第二十九话《创建图片副本》
查看>>
Android简易实战教程--第三十二话《使用Lrucache和NetworkImageView加载图片》
查看>>
Oracle 11g Articles
查看>>
Android直接用手机打包apk!
查看>>
vue中created、mounted等方法整理
查看>>
如何连接oracle数据库及故障解决办法
查看>>
如何给ocx,dll控件进行数字签名
查看>>
新开通博客【人工置顶】
查看>>
mongoose学习参考
查看>>
python 输入列的名字,直接可以得到图像
查看>>
ztree根据关键字模糊搜索
查看>>