本文来源为: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. 3.2---最小栈(CC150)

    //思路:入栈时不是最小值,永远都没机会成为最小值. import java.util.Stack; class MinStack { private Stack<Integer> sta ...

  2. 一个简单的log

    #pragma once #include <windows.h> #include <process.h> class CLogger { public: static CR ...

  3. Linux--多网卡的7种Bond模式

    网卡bond是通过把多张网卡绑定为一个逻辑网卡,实现本地网卡的冗余,带宽扩容和负载均衡.在应用部署中是一种常用的技术,我们公司基本所有的项目相关服务器都做了bond,这里总结整理,以便待查. bond ...

  4. vim常用命令(iOS)

    iOS下vim的使用: vim 的三种模式: .一般模式(默认) .插入模式(写文字) .命令行模式(保存) 各种模式的功能区分如下: .一般模式:控制屏幕光标的移动,字符和光标的删除,移动复制某区段 ...

  5. poj 2403

    http://poj.org/problem?id=2403 题意:就是给你m个单词,以及n段对话.每一个单词都有所对应的价值.求对话中的价值总和 题解:很简单,就是用单词和价值对应起来,然后再寻找就 ...

  6. ACM/ICPC 之 BFS+状态压缩(POJ1324(ZOJ1361))

    求一条蛇到(1,1)的最短路长,题目不简单,状态较多,需要考虑状态压缩,ZOJ的数据似乎比POj弱一些 POJ1324(ZOJ1361)-Holedox Moving 题意:一条已知初始状态的蛇,求其 ...

  7. NetBeans常用快捷键

    Ctrl+Space:代码自动完成,在Windows下通常与输入法切换有冲突,我改成了ALT+2: Ctrl+/:注释&取消注释: Alt+Shift+F:编辑器自动格式,由于三个组合键不好按 ...

  8. codeforces 515C. Drazil and Factorial 解题报告

    题目链接:http://codeforces.com/problemset/problem/515/C 题目意思:给出含有 n 个只有阿拉伯数字的字符串a(可能会有前导0),设定函数F(a) = 每个 ...

  9. php继承、多态

    继承: 概念:子类可以继承父类的一切 特点:单继承:一个子类只能有一个父类,一个父类可以派生出多个子类 方法重写:在子类里面对父类的方法进行重写. 重写:override 重载,编译多态:overlo ...

  10. 火狐----此地址使用了一个通常用于网络浏览以外的端口。出于安全原因,Firefox 取消了该请求。

    FirFox打开80以外的端口,会弹出以下提示: “此地址使用了一个通常用于网络浏览以外的端口.出于安全原因,Firefox 取消了该请求.”.经网上搜索,解决方法如下: 在Firefox地址栏输入a ...