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. SpringMVC上传多文件

    springMVC实现 多文件上传的方式有两种,一种是我们经常使用的以字节流的方式进行文件上传,另外一种是使用springMVC包装好的解析器进行上传.这两种方式对于实 现多文件上传效率上却有着很大的 ...

  2. 漫谈WebQQ 协议

    阅读目录        1,WEBQQ的登陆协议 2,传说中的心跳包 3,获得群,好友, 4实战(盗号-外挂-广告)     要说怎么突然研究起WEBQQ,也是比较偶然的机会,因为前一份工作专注于B2 ...

  3. 高并发服务器架构--SEDA架构分析

    纯粹转发,没有深入研究,转自:SEDA架构笔记 百牛信息技术bainiu.ltd整理发布于博客园  一.传统并发模型的缺点 基于线程的并发 特点:每任务一线程直线式的编程使用资源昂高,context切 ...

  4. 交通规划_dijkstra

    问题描述 G国国王来中国参观后,被中国的高速铁路深深的震撼,决定为自己的国家也建设一个高速铁路系统. 建设高速铁路投入非常大,为了节约建设成本,G国国王决定不新建铁路,而是将已有的铁路改造成高速铁路. ...

  5. Collection View Programming Guide for iOS---(二)----Collection View Basics

      Collection View Basics Collection View 基础 To present its content onscreen, a collection view coope ...

  6. poj1163 【记忆化搜索·水】

    题意: 一个这样的三角形,他可以往下的左或者往下的右走.求一个在最后一行的最大. 思路: 额...就是搜一下..记录一下...肯定有重合的情况. code- //#include <bits/s ...

  7. bzoj 1022: [SHOI2008]小约翰的游戏John【anti-nim】

    如果全是1,那么n是奇数先手必败 否则,xor和为0先手必败 证明见 https://www.cnblogs.com/Wolfycz/p/8430991.html #include<iostre ...

  8. touch的基本用法

    touch的基本功能是改变文件的时间戳,以下是三种常用用法: 1.创建一个空文件 以当前时间为时间戳创建一个空文件.$ touch touch.txt //touch.txt不存在 2.更改文件时间戳 ...

  9. ASI框架的使用

    iOS开发网络篇—简单介绍ASI框架的使用 说明:本文主要介绍网络编程中常用框架ASI的简单使用. 一.ASI简单介绍 ASI:全称是ASIHTTPRequest,外号“HTTP终结者”,功能十分强大 ...

  10. 无向图的边双连通分量(EBC)

    嗯,首先边双连通分量(双连通分量之一)是:在一个无向图中,去掉任意的一条边都不会改变此图的连通性,即不存在桥(连通两个边双连通分量的边),称作边双连通分量.一个无向图的每一个极大边双连通子图称作此无向 ...