初识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; } ...
随机推荐
- angular4 路由重用策略 RouterReuseStrategy
单页面应用现在是主流,随之而来的缺点:页面间切换时不能保存状态 angular4出了一个RouteReuseStrategy路由重用策略可以让组件所有的state和渲染好的html存起来,然后在切回去 ...
- java图形验证码生成工具类及web页面校验验证码
最近做验证码,参考网上案例,发现有不少问题,特意进行了修改和完善. 验证码生成器: import javax.imageio.ImageIO; import java.awt.*; import ja ...
- linux挂载点 和 文件系统$ mount$ cat /etc/fstab$ vgs$ pvs$ lvs$ df -h$ lsof +D / /* beware not to kill your box */
$ mount$ cat /etc/fstab$ vgs$ pvs$ lvs$ df -h$ lsof +D / /* beware not to kill your box */ 一共挂载了多少文件 ...
- Sublime Text Version 3.2.1(Build 3207)注册
Sublime Text Version 3.2.1, Build 3207 一. host添加地址 C:\Windows\System32\drivers\etc\hosts 127.0.0.1 l ...
- transact和onTransact的区别
转:http://blog.csdn.net/sergeycao/article/details/52585411 谈transact 和onTransact需要先聊聊iBinder IBinder是 ...
- 杨柳絮-Info:阜阳市多举措治理杨柳絮问题
ylbtech-杨柳絮-Info:阜阳市多举措治理杨柳絮问题 1.返回顶部 1. 阜阳市多举措治理杨柳絮问题 2019-4-15 10:34| 发布者: 戴斐 | 查看: 56407| 评论: 0|原 ...
- 记UWP开发——多线程操作/并发操作中的坑
一切都要从新版风车动漫UWP的图片缓存功能说起. 起因便是风车动漫官网的番剧更新都很慢,所以图片更新也非常慢.在开发新版的过程中,我很简单就想到了图片多次重复下载导致的资源浪费问题. 所以我给app加 ...
- SDUT-3400_数据结构实验之排序三:bucket sort
数据结构实验之排序三:bucket sort Time Limit: 250 ms Memory Limit: 65536 KiB Problem Description 根据人口普查结果,知道目前淄 ...
- PLAY2.6-SCALA(十一) 模板常用场景
1.布局 声明一个views/main.scala.html模板作为主布局模板 @(title: String)(content: Html) <!DOCTYPE html> <ht ...
- mysqldump命令之数据库迁移
格式说明如下: mysqldump -h源主机IP -u源主机用户 -p源主机用户密码 数据库名 | mysql -h目标主机IP -u目标主机用户 -p目标用户密码 数据库名