初识block
我们可以把Block当做Objective-C的匿名函数。Block允许开发者在两个对象之间将任意的语句当做数据进行传递,往往这要比引用定义在别处的函数直观。另外,block的实现具有封闭性(closure),而又能
“”
本文转自破船的博客:
小引
Got Blocks。虽然之前也有接触过block,不过没有深入完整的学习过,借此机会来学习一下,顺便翻译几篇block相关的文章,本文是第一篇,算是block的入门。本文的最后延伸阅读给出了4篇相关文章,不出意外的话,本周大家能看到对应的中文版。
- // main.m
- #import <Foundation/Foundation.h>
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- // Declare the block variable
- double (^distanceFromRateAndTime)(double rate, double time);
- // Create and assign the block
- distanceFromRateAndTime = ^double(double rate, double time) {
- return rate * time;
- };
- // Call the block
- double dx = distanceFromRateAndTime(35, 1.5);
- NSLog(@"A car driving 35 mph will travel "
- @"%.2f miles in 1.5 hours.", dx);
- }
- return 0;
- }
- double (^randomPercent)(void) = ^ {
- return (double)arc4random() / 4294967295;
- };
- NSLog(@"Gas tank is %.1f%% full",
- randomPercent() * 100);
- NSString *make = @"Honda";
- NSString *(^getFullCarName)(NSString *) = ^(NSString *model) {
- return [make stringByAppendingFormat:@" %@", model];
- };
- NSLog(@"%@", getFullCarName(@"Accord")); // Honda Accord

- NSString *make = @"Honda";
- NSString *(^getFullCarName)(NSString *) = ^(NSString *model) {
- return [make stringByAppendingFormat:@" %@", model];
- };
- NSLog(@"%@", getFullCarName(@"Accord")); // Honda Accord
- // Try changing the non-local variable (it won't change the block)
- make = @"Porsche";
- NSLog(@"%@", getFullCarName(@"911 Turbo")); // Honda 911 Turbo
- __block NSString *make = @"Honda";

local variable)类似,用__block修饰符声明的变量可以记录着block多次调用的结果。例如下面的代码创建了一个block,在block中对i进行累加。
- __block int i = 0;
- int (^count)(void) = ^ {
- i += 1;
- return i;
- };
- NSLog(@"%d", count()); // 1
- NSLog(@"%d", count()); // 2
- NSLog(@"%d", count()); // 3
- // Car.h
- #import <Foundation/Foundation.h>
- @interface Car : NSObject
- @property double odometer;
- - (void)driveForDuration:(double)duration
- withVariableSpeed:(double (^)(double time))speedFunction
- steps:(int)numSteps;
- @end
- // Car.m
- #import "Car.h"
- @implementation Car
- @synthesize odometer = _odometer;
- - (void)driveForDuration:(double)duration
- withVariableSpeed:(double (^)(double time))speedFunction
- steps:(int)numSteps {
- double dt = duration / numSteps;
- for (int i=1; i<=numSteps; i++) {
- _odometer += speedFunction(i*dt) * dt;
- }
- }
- @end
- // main.m
- #import <Foundation/Foundation.h>
- #import "Car.h"
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- Car *theCar = [[Car alloc] init];
- // Drive for awhile with constant speed of 5.0 m/s
- [theCar driveForDuration:10.0
- withVariableSpeed:^(double time) {
- return 5.0;
- } steps:100];
- NSLog(@"The car has now driven %.2f meters", theCar.odometer);
- // Start accelerating at a rate of 1.0 m/s^2
- [theCar driveForDuration:10.0
- withVariableSpeed:^(double time) {
- return time + 5.0;
- } steps:100];
- NSLog(@"The car has now driven %.2f meters", theCar.odometer);
- }
- return 0;
- }
- // Car.h
- #import <Foundation/Foundation.h>
- // Define a new type for the block
- typedef double (^SpeedFunction)(double);
- @interface Car : NSObject
- @property double odometer;
- - (void)driveForDuration:(double)duration
- withVariableSpeed:(SpeedFunction)speedFunction
- steps:(int)numSteps;
- @end
初识block的更多相关文章
- Block系列1:初识block
//-------1.定义函数----- //1.函数 int sum(int a,int b) { return a+b; } //------------------2.声明--------- / ...
- iOS开发技巧系列---使用链式编程和Block来实现UIAlertView
UIAlertView是iOS开发过程中最常用的控件之一,是提醒用户做出选择最主要的工具.在iOS8及后来的系统中,苹果更推荐使用UIAlertController来代替UIAlertView.所以本 ...
- [Objective-C] Block实现回调和简单的学习思考
初识Block的时候,总觉得其很可怕,因为看不懂其运行原理,所以用起来总是觉得不安全.关于Block的语法,等我把手里的资料全部看完,整理好再发出来.这次先看看用Block怎么实现回调. 新博客:wo ...
- block的初识
block的介绍: Block是iOS4.0之后新增的一种语法结构,也称为“闭包(closure)”. SDK4.0新增的API大量使用了Block. Block是一个匿名的函数代码块,此代码 ...
- 初识Hadoop
第一部分: 初识Hadoop 一. 谁说大象不能跳舞 业务数据越来越多,用关系型数据库来存储和处理数据越来越感觉吃力,一个查询或者一个导出,要执行很长 ...
- Python自动化 【第十八篇】:JavaScript 正则表达式及Django初识
本节内容 JavaScript 正则表达式 Django初识 正则表达式 1.定义正则表达式 /.../ 用于定义正则表达式 /.../g 表示全局匹配 /.../i 表示不区分大小写 /.../m ...
- 初识Hadoop入门介绍
初识hadoop入门介绍 Hadoop一直是我想学习的技术,正巧最近项目组要做电子商城,我就开始研究Hadoop,虽然最后鉴定Hadoop不适用我们的项目,但是我会继续研究下去,技多不压身. < ...
- hadoop初识
搞什么东西之前,第一步是要知道What(是什么),然后是Why(为什么),最后才是How(怎么做).但很多开发的朋友在做了多年项目以后,都习惯是先How,然后What,最后才是Why,这样只会让自己变 ...
- IOS之UI -- UITableView -- 1 -- 相关初识
*:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } ...
随机推荐
- jQ-点击查看更多
<style type="text/css"> .hi { width: 200px; height: 18vw; background-color: pink; fo ...
- GIT → 10:基于IntelliJ IDEA的Git 操作
GIT → 10:基于IntelliJ IDEA的Git 操作
- storm 为什么要存在不透明分区事务
不透明分区事务不区分发新消息还是旧消息,全部用emitPartitionBatch搞定,虽然 emitPartitionBatch返回的X应该是下一批次供自己使用(emitPartitionBatch ...
- Legal or Not HDU - 3342 (拓扑排序)
注意点: 输入数据中可能有重复,需要进行处理! #include <stdio.h> #include <iostream> #include <cstring> ...
- loadrunner分析之-网页、网络、资源分析
在Web Page Diagnostics(网页分析)中当在场景中打开Diagnostics菜单下的Web Page Diagnostics功能,就能得到网页分析组图.通过这个图,可以对事务的组成进行 ...
- Centos6.x终端中文乱码
locale LANG LC_*的默认值,是最低级别的设置,如果LC_*没有设置,则使用该值.类似于 LC_ALL. LC_ALL 它是一个宏,如果该值设置了,则该值会覆盖所有LC_*的设置值.注意 ...
- ubuntu上安装字体
# fc-list # sudo apt-get -y install fontconfig xfonts-utils # sudo cp XXX.ttf /usr/shar ...
- 一文读懂JVM
(一)JVM 基础知识 1)Java 是如何实现跨平台的? 注意:跨平台的是 Java 程序,而不是 JVM.JVM 是用 C/C++ 开发的,是编译后的机器码,不能跨平台,不同平台下需要安装不同版本 ...
- $.inArray()方法
$.inArray() 函数用于在数组中查找指定值,并返回它的索引值(如果没有找到,则返回-1) 提示:源数组不会受到影响,过滤结果只反映在返回的结果数组中. 语法 $.inArray( value, ...
- 关于sublime text2的一些问题(为解决)
1. 编写markdown文件后,如何转成pdf ? 2. 执行程序时,如何在控制台输入数据?