初识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; } ...
随机推荐
- 基础架构:一条SQL查询语句是如何执行的?
https://time.geekbang.org/column/article/68319?code=pEYaxHnjO23LQHW4CJgL706EXlpAJnbOOiT2y42cWwU%3D 这 ...
- 门诊叫号系统系列-1.语音叫号 .net c#
最近收到一个需求,朋友诊室需要做到门诊叫号,流程如下:病人选择医生-刷身份证排队-医生点击病人姓名叫号. 经过团队的努力,一个简易的门诊叫号系统已经完成.现在把各个功能记录下来,方便以后查看. 1.语 ...
- php7不再支持HTTP_RAW_POST_DATA,微信支付$GLOBALS[‘HTTP_RAW_POST_DATA’]获取不到数据,
升级到php7后, 发现旧的web系统有些问题, 查看后才发现原来是php7不再支持HTTP_RAW_POST_DATA 原来系统一些地方, 使用$GLOBALS[‘HTTP_RAW_POST_DAT ...
- python3.7 安装gensim使用word2Vec库
应用的文章(个人试验过,完全正确):https://radimrehurek.com/gensim/index.html#install
- Mybatis - plus 配置与运用
Mybatis - plus mybatis-plus 官方文档 1.配置 引入对应的文件包,spring boot + mybatis 需添加依赖文件如下: <dependencies> ...
- 使用SQLyog将Mysql中的表导出为Excel
有时会有这样的需求:将MYSQL数据库中的某个表格导出,存为Excel文件.下面介绍步骤: 1.打开SQLyog,选中要导出的表 2.右键--备份/导出--导出表数据作为... 3.如图选择 Exce ...
- c中函数指针和回调函数
函数指针: 指向函数的指针.(定义的函数会分配一块内存,同变量一样存在首地址)示例如下: int Func(int x); /*声明一个函数*/ int (*p) (int x); /*定义一个函数指 ...
- 如何用KNIME进行情感分析
Customer Intelligence Social Media Finance Credit Scoring Manufacturing Pharma / Health Care Retail ...
- 【转载】ubuntu下编写字符设备驱动程序-入门篇
在ubuntu初学驱动,觉得挺有用的. http://www.eefocus.com/jefby1990/blog/13-02/291628_c39b8.html
- PHP实现redis限制单ip、单用户的访问次数功能
本文实例讲述了PHP实现redis限制单ip.单用户的访问次数功能.分享给大家供大家参考,具体如下: 有时候我们需要限制一个api或页面访问的频率,例如单ip或单用户一分钟之内只能访问多少次 类似于这 ...