本文来源为:developer.apple.com,仅仅是博主练习排版所用。

Getting Started with Blocks

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

Declaring and Using a 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):

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

The example is explained in the following illustration:


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:

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

printf("%d", myBlock(3));
// prints "21"

Using a Block Directly

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.

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

qsort_b(myCharacters, 3, sizeof(char *), ^(const void *l, const void *r) {
char *left = *(char **)l;
char *right = *(char **)r;
return strncmp(left, right, 1);
});

Blocks with Cocoa

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 sortedArrayUsingComparator:. The method takes a single argument—the block. For illustration, in this case the block is defined as an NSComparator local variable:

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(0, [string1 length]);
return [string1 compare:string2 options:comparisonOptions range:string1Range locale:currentLocale];
};

NSArray *finderSortArray = [stringsArray sortedArrayUsingComparator:finderSortBlock];
NSLog(@"finderSortArray: %@", finderSortArray);

/*
Output: NSArray *stringArray = @[ @"string 1", @"string 2", @"string21", @"string 12", @"string 02"];

NSComparator finderSortBlock = ^(id string1, id string2){
	NSRange string1Range = NSMakeRange(0, [string1 length]);
	return [string1 compare:string2 options:comparisonOptions range:string1Range locale:currentLocale];
};

NSArray *findSortArray = [stringArray sortedArrayUsingComparator:finderSortBlock];
NSLog(@"...:%@",findSortArray);
finderSortArray: (
"string 1",
"String 02",
"String 11",
"string 12",
"String 21"
)
*/

__block Variables

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:

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 = 0;

NSArray *diacriticInsensitiveSortArray = [stringsArray sortedArrayUsingComparator:^(id string1, id string2) {

NSRange string1Range = NSMakeRange(0, [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.

Getting Started with Blocks的更多相关文章

  1. 从Script到Code Blocks、Code Behind到MVC、MVP、MVVM

    刚过去的周五(3-14)例行地主持了技术会议,主题正好是<UI层的设计模式——从Script.Code Behind到MVC.MVP.MVVM>,是前一天晚上才定的,中午花了半小时准备了下 ...

  2. 【POJ-1390】Blocks 区间DP

    Blocks Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 5252   Accepted: 2165 Descriptio ...

  3. 开发该选择Blocks还是Delegates

    前文:网络上找了很多关于delegation和block的使用场景,发现没有很满意的解释,后来无意中在stablekernel找到了这篇文章,文中作者不仅仅是给出了解决方案,更值得我们深思的是作者独特 ...

  4. poj 1390 Blocks

    poj 1390 Blocks 题意 一排带有颜色的砖块,每一个可以消除相同颜色的砖块,,每一次可以到块数k的平方分数.问怎么消能使分数最大.. 题解 此题在徐源盛<对一类动态规划问题的研究&g ...

  5. Java 同步代码块 - Synchronized Blocks

    java锁实现原理: http://blog.csdn.net/endlu/article/details/51249156 The synchronized keyword can be used ...

  6. 区块 Blocks

    Structure / Blocks / Demonstrate block regions

  7. 使用Code::blocks在windows下写网络程序

    使用Code::blocks在windows下写网络程序 作者 He YiJun – storysnail<at>gmail.com 团队 ls 版权 转载请保留本声明! 本文档包含的原创 ...

  8. Code::Blocks配置GTK+2和GTK+3

    Code::Blocks配置GTK+2和GTK+3 作者 He YiJun – storysnail<at>gmail.com 团队 ls 版权 转载请保留本声明! 本文档包含的原创代码根 ...

  9. [翻译]理解Ruby中的blocks,Procs和lambda

    原文出处:Understanding Ruby Blocks, Procs and Lambdas blocks,Procs和lambda(在编程领域被称为闭包)是Ruby中很强大的特性,也是最容易引 ...

  10. Java Synchronized Blocks

    From http://tutorials.jenkov.com/java-concurrency/synchronized.html By Jakob Jenkov   A Java synchro ...

随机推荐

  1. Apache shutdown unexpectedly启动错误解决方法

    这个问题比较常见, 通常是80.443端口被占用 cmd 通过运行apache/bin/httpd.exe 打印如下log: (OS 10048)通常每个套接字地址(协议/网络地址/端口)只允许使用一 ...

  2. Eclipse不给提示no default proposals

    解决方法: (1),找到工程所在的workspace,删除.metadata配置文件. (2),启动eclipse,重新定位到先前的workspace目录置,重建同名工程(不要删除原来的工程,只要建立 ...

  3. win8内置管理员用户无法激活此应用

    在运行中输入:“gpedit.msc”,就会启动组策略编辑器, 计算机配置 --> Windows设置 --> 安全设置 --> 本地策略 -->  安全选项  ::::  用 ...

  4. MySQL 四种事务隔离级的说明

    很早之前写的文章,重新回顾和学习下: 按照SQL:1992 事务隔离级别,InnoDB默认是可重复读的(REPEATABLE READ).MySQL/InnoDB 提供SQL标准所描述的所有四个事务隔 ...

  5. MongoDB 分片的原理、搭建、应用

    一.概念: 分片(sharding)是指将数据库拆分,将其分散在不同的机器上的过程.将数据分散到不同的机器上,不需要功能强大的服务器就可以存储更多的数据和处理更大的负载.基本思想就是将集合切成小块,这 ...

  6. 【Android】如何将eclipse工程导入studio

    1.eclipse工程右键->export->Generate Gradle build files 2.studio->New->import project->选择工 ...

  7. 关于C语言中的转义字符

    1.转义字符的分类 1. 1一般转义字符 这种转义字符,虽然在形式上由两个字符组成,但只代表一个字符.常用的一般转义字符为: \a     \n     \t     \v     \b     \r ...

  8. 解决sqlite3_key的问题

    报错内容显示如下: ld: warning: ignoring file /Users/rowling/Library/Developer/Xcode/DerivedData/zhinengbango ...

  9. September 29th 2016 Week 40th Thursday

    Prosperity discovers vice, adversity virtue. 得意时露瑕疵,逆境中见品质. I wish I would have someone like you, fr ...

  10. August 20th 2016 Week 34th Saturday

    Everything you see exists together in a delicate balance. 你所看到的一切都处于微妙的平衡中. Seeking for balance in l ...