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

(译)IOS block编程指南 2 block开始的更多相关文章

  1. (译)IOS block编程指南 1 介绍

    Introduction(介绍) Block objects are a C-level syntactic and runtime feature. They are similar to stan ...

  2. iOS多线程编程指南

    iOS多线程编程指南(拓展篇)(1) 一.Cocoa 在Cocoa上面使用多线程的指南包括以下这些: (1)不可改变的对象一般是线程安全的.一旦你创建了它们,你可以把这些对象在线程间安全的传递.另一方 ...

  3. (译文)IOS block编程指南 4 声明和创建blocks

    Declaring and Creating Blocks (声明和创建blocks) Declaring a Block Reference (声明一个block引用) Block variable ...

  4. (译文)IOS block编程指南 3 概念总览

    Conceptual Overview(概览) Block objects provide a way for you to create an ad hoc function body as an ...

  5. iOS多线程编程指南(一)关于多线程编程(转)

    原文:http://www.dreamingwish.com/article/ios-multi-threaded-programming-a-multi-threaded-programming.h ...

  6. iOS 并发编程指南

    iOS Concurrency Programming Guide iOS 和 Mac OS 传统的并发编程模型是线程,不过线程模型伸缩性不强,而且编写正确的线程代码也不容易.Mac OS 和 iOS ...

  7. <译>Spark Sreaming 编程指南

    Spark Streaming 编程指南 Overview A Quick Example Basic Concepts Linking Initializing StreamingContext D ...

  8. iOS ---Extension编程指南

    当iOS 8.0和OS X v10.10发布后,一个全新的概念出现在我们眼前,那就是应用扩展.顾名思义,应用扩展允许开发者扩展应用的自定义功能和内容,能够让用户在使用其他app时使用该项功能.你可以开 ...

  9. iOS多线程编程指南(二)线程管理

    当应用程序生成一个新的线程的时候,该线程变成应用程序进程空间内的一个实体.每个线程都拥有它自己的执行堆栈,由内核调度独立的运行时间片.一个线程可以和其他线程或其他进程通信,执行I/O操作,甚至执行任何 ...

随机推荐

  1. 基于jQuery仿淘宝产品图片放大镜特效

    在开发商城的时候,往往会用到图片的放大功能,这里把自己在近期项目中使用的放大镜特效做一下总结(非插件). 放大镜效果 常用的js组件jquery.imagezoom,jquery.jqzoom,jqu ...

  2. string类中运算符重载实现

    C++中预定义的加.减等运算符的操作对象只能是基本的数据类型.如果要在用户自定义的类型对象上应用同样的运算符,就需要通过运算符重载来重新定义其实现,使它能够用于自定义类型执行特定的操作,所以运算符重载 ...

  3. Python-Django使用MemcachedCache缓存

    最近工作中使用到缓存,简单记录之... 关于django的几种缓存方式,就不在做介绍了,网上一搜一大把:1.8.2官方文档, Django 缓存,Python菜鸟之路:django缓存 学习了之后,选 ...

  4. Python实现的一个简单LRU cache

    起因:我的同事需要一个固定大小的cache,如果记录在cache中,直接从cache中读取,否则从数据库中读取.python的dict 是一个非常简单的cache,但是由于数据量很大,内存很可能增长的 ...

  5. 洛谷P1113杂物——DP

    题目:https://www.luogu.org/problemnew/show/P1113 每个任务的时间就是准备工作中完成最晚的那个的时间再加上自己的时间. 代码如下: #include<i ...

  6. 微信小程序服务类目大坑:特殊行业服务类目所需资质材料

    作为一个技术开发人员,遇到特殊行业服务类目所需资质材料,只能叫苦连天了,妈的,这个不是技术可以解决的问题,如果技术可以解决的问题都不是问题. 百牛信息技术bainiu.ltd整理发布于博客园 特殊行业 ...

  7. 介绍一下Extern “C”,它的作用是什么?

    Extern “C”是由C++提供的一个连接交换指定符号,用于告诉C++这段代码是C函数.这是因为C++编译后库中函数名会变得很长,与C生成的不一致,造成C++不能直接调用C函数,加上extren “ ...

  8. HDOJ4857【拓扑排序】

    首先 CLJ ORZ 这道题做了两次,第一次瞎搞... 第二次,好吧,骄傲地说水过... 题意:不说了: 思路: 题目默认是小的在前面,那么就是反向建图,每次排序拿大的出来: 第一次做的时候,我记得我 ...

  9. 洛谷 P4125 [WC2012]记忆中的水杉树【扫描线+set+线段树】

    我没有找到能在bzojAC的代码--当然我也WA了--但是我在洛谷过了,那就假装过了吧 minmax线段树一开始写的只能用min更新min,max更新max,实际上是可以互相更新的-- 首先看第二问, ...

  10. 鸟哥私房菜基础篇:安裝 CentOS7.x习题

    猫宁!!! 参考链接:http://linux.vbird.org/linux_basic/0157installcentos7.php 鸟哥是为中国信息技术发展做出巨大贡献的人. 1-Linux的目 ...