• what is block

Blocks are a language-level feature added to C, Objective-C and C++, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary. They also have the ability to capture values from the enclosing scope, making them similar to closures or lambdas in other programming languages。

块是一个语言级功能添加到C,Objective-C和C + +中,这允许你创建的代码的不同部分可以被传递到方法或函数,如果他们的值。块是Objective-C的对象,这意味着它们可以被添加到像的 NSArray或NSDictionary的集合。他们还必须从封闭范围捕捉值,使它们类似于其他编程语言倒闭或lambda表达式的能力。

  • block function

A block is an anonymous inline collection of code that:

块是一个匿名代码内嵌集合

  1.Has a typed argument list just like a function。有一个类型参数列表就像一个函数

  2.Has an inferred or declared return type。有一个推断或声明的返回类型

  3.Can capture state from the lexical scope within which it is defined。可以从内部定义它的词法范围捕捉状态

  4.Can optionally modify the state of the lexical scope。可以选择修改的词法作用域的状态

  5.Can share the potential for modification with other blocks defined within the same lexical scope。可以用相同的词法范围内定义的其它块共享进行修改的可能性

  6.Can continue to share and modify state defined within the lexical scope (the stack frame) after the lexical scope (the stack frame) has been destroyed。可以继续  分享和修改词法范围(堆栈帧)中定义的状态后,词法范围(堆栈帧)已被破坏

You can copy a block and even pass it to other threads for deferred execution (or, within its own thread, to a runloop). The compiler and runtime arrange that all variables referenced from the block are preserved for the life of all copies of the block. Although blocks are available to pure C and C++, a block is also always an Objective-C object.

您可以复制块,甚至把它传递给其他线程的延迟执行(或者,在它自己的线程,在runloop)。该编译器和运行安排,从块中引用的所有变量都保存在块的所有副本的使用寿命。虽然块可用于纯C和C + +中,一个块也总是一个Objective-C的对象。

  • define block

Block variables hold references to blocks. You declare them using syntax similar to that you use to declare a pointer to a function, except that you use ^ instead of *. The block type fully interoperates with the rest of the C type system. The following are all valid block variable declarations:

块变量持有引用块。你声明它们使用的语法类似于用于声明一个指向函数的指针,除非你使用^,而不是* 。块类型完全互操作与C型系统的其余部分。以下是所有有效块的变量声明:

oid (^blockReturningVoidWithVoidArgument)(void);
int (^blockReturningIntWithIntAndCharArguments)(int, char);
void (^arrayOfTenBlocksReturningVoidWithIntArgument[10])(int);

blocks also support variadic (...) arguments. A block that takes no arguments must specify void in the argument list.

块还支持可变参数(...)的参数。块,它没有参数必须在参数列表中指定void

Blocks are designed to be fully type safe by giving the compiler a full set of metadata to use to validate use of blocks, parameters passed to blocks, and assignment of the return value. You can cast a block reference to a pointer of arbitrary type and vice versa. You cannot, however, dereference a block reference via the pointer dereference operator (*)—thus a block's size cannot be computed at compile time.

块被设计为完全类型安全的通过给编译器一套完整的元数据的使用,以验证使用的块,传递给块参数和返回值的分配。你可以投一个块引用任意类型的指针,反之亦然。你可以没有,但是,通过解引用指针解引用操作符(*)这样一个块的大小的块参照不能在编译时计算。

You can also create types for blocks—doing so is generally considered to be best practice when you use a block with a given signature in multiple places:

您还可以创建类型为块,这样做通常被认为是最佳实践,当你在多个地方使用与给定的签名块。

typedef float (^MyBlockType)(float, float);
 
MyBlockType myFirstBlock = // ... ;
MyBlockType mySecondBlock = // ... ;
  • Blocks and Variable

Within the block object’s body of code, variables may be treated in five different ways.

You can reference three standard types of variable, just as you would from a function:

  1.Global variables, including static locals。 全局变量, 包括全局静态变量

  2.Global functions (which aren’t technically variables)。全局函数(不是技术上的变量)

  3.Local variables and parameters from an enclosing scope。一个封闭的范围局部变量和参数

Blocks also support two other types of variable:

  1. At function level are __block variables. These are mutable within the block (and the enclosing scope) and are preserved if any referencing block is copied to the heap.在函数级别是__block变量。这是块内可变(和封闭范围),并保留如有引用块被复制到堆

  2. const imports. 引入的const修饰的变量

Finally, within a method implementation, blocks may reference Objective-C instance variables—see “Object and Block Variables.”

The following rules apply to variables used within a block:

  1. Global variables are accessible, including static variables that exist within the enclosing lexical scope.

  2. Parameters passed to the block are accessible (just like parameters to a function).

  3. Stack (non-static) variables local to the enclosing lexical scope are captured as const variables.

    Their values are taken at the point of the block expression within the program. In nested blocks, the value is captured from the nearest enclosing scope.

  4. Variables local to the enclosing lexical scope declared with the __block storage modifier are provided by reference and so are mutable.

    Any changes are reflected in the enclosing lexical scope, including any other blocks defined within the same enclosing lexical scope. These are discussed in more detail in “The __block Storage Type.”

  5. Local variables declared within the lexical scope of the block, which behave exactly like local variables in a function.

    Each invocation of the block provides a new copy of that variable. These variables can in turn be used as const or by-reference variables in blocks enclosed within the block.

  • The __block Storage Type

You can specify that an imported variable be mutable—that is, read-write— by applying the __block storage type modifier. __block storage is similar to, but mutually exclusive of, the register, auto, and static storage types for local variables.

__block variables live in storage that is shared between the lexical scope of the variable and all blocks and block copies declared or created within the variable’s lexical scope. Thus, the storage will survive the destruction of the stack frame if any copies of the blocks declared within the frame survive beyond the end of the frame (for example, by being enqueued somewhere for later execution). Multiple blocks in a given lexical scope can simultaneously use a shared variable.

As an optimization, block storage starts out on the stack—just like blocks themselves do. If the block is copied using Block_copy (or in Objective-C when the block is sent a copy), variables are copied to the heap. Thus, the address of a __block variable can change over time.

作为一种优化,块存储开出的栈就像块本身做。如果块使用Block_copy(或Objective-C中,当块被发送副本)复制,变量将被复制到堆。因此,__block变量的地址可以随时间而改变

There are two further restrictions on __block variables: they cannot be variable length arrays, and cannot be structures that contain C99 variable-length arrays.

这里是关于__block变量的两个进一步限制:它们不能是可变长度数组;不能包含C99可变长数组结构;

  • using block

  1. 定义局部块,现做现用。 见代码:

2. 使用块做为函数的参数传递。

ios专题 -block用法的更多相关文章

  1. iOS中block的用法 以及和函数用法的区别

    ios中block的用法和函数的用法大致相同 但是block的用法的灵活性更高: 不带参数的block: void ^(MyBlock)() = ^{}; 调用的时候  MyBlock(); 带参数的 ...

  2. iOS之block

    1. Block的声明和线程安全Block属性的声明,首先需要用copy修饰符,因为只有copy后的Block才会在堆中,栈中的Block的生命周期是和栈绑定的,可以参考之前的文章(iOS: 非ARC ...

  3. iOS 中Block以及Blocks的使用,闭包方法调用

    OC: -(void)dataWithUrl:(NSString*)string AndId:(NSInteger)id returnName:(void(^)(NSString*name))back ...

  4. iOS开发--Block

    iOS开发--Block 1.什么是Block,block 的作用 ui开发和网络常见功能实现回调,按钮的事件处理方法是回调方法以及网络下载后的回调处理 (1)按钮 target-action   一 ...

  5. iOS开发——Block详解

    iOS开发--Block详解 1. Block是什么 代码块 匿名函数 闭包--能够读取其他函数内部变量的函数 函数变量 实现基于指针和函数指针 实现回调的机制 Block是一个非常有特色的语法,它可 ...

  6. IOS NSUserDefaults 讲解 用法

    IOS NSUserDefaults 讲解 用法    NSUserDefaults适合存储轻量级的本地数据,比如要保存一个登陆界面的数据,用户名.密码之类的,个人觉得使用NSUserDefaults ...

  7. ios开发 block语句块

    ios开发 block语句块 1.block 理解为匿名函数 2.block变量的定义 //定义block变量,^表示定义block //技巧:函数名左右加括号,在函数名前面在加^ void (^bl ...

  8. iOS中Block介绍(一)基础

    ios开发block的使用指南,以及深入理解block的内存管理,也适用于osx开发.讨论范围:block的使用,内存管理,内部实现.不包含的内容:gc arc下的block内存,block在c++中 ...

  9. iOS中Block介绍 基础

    ios开发block的使用指南,以及深入理解block的内存管理,也适用于osx开发.讨论范围:block的使用,内存管理,内部实现.不包含的内容:gc arc下的block内存,block在c++中 ...

  10. iOS中block类型大全

    iOS中block类型大全 typedef的block 作为属性的block 作为变量的block 作为方法变量入参的block 作为方法参数的block 无名block 内联函数的block 递归调 ...

随机推荐

  1. ubuntu下arm-linux-gcc安装

    我下载的地址随便找的,4.4.3版本的,地址:http://www.cr173.com/soft/42654.html#address 1.我放在了/work/tools/ 2.sudo tar  x ...

  2. Java笔记(二十)……线程间通信

    概述 当需要多线程配合完成一项任务时,往往需要用到线程间通信,以确保任务的稳步快速运行 相关语句 wait():挂起线程,释放锁,相当于自动放弃了执行权限 notify():唤醒wait等待队列里的第 ...

  3. HDU-1255 覆盖的面积 覆盖的矩形面积并

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1255 需要保存区间覆盖线>=2的线段的长度,根据情况来更新... //STATUS:C++_AC ...

  4. H.264 Profile、Level、Encoder三张简图 (fps = AVCodecContext->time_base.den / AVCodecContext->time_base.num)

    H.264 Profiles Profiles are sets of capabilities. If your black box only supports the Baseline profi ...

  5. 问题-[DelphiXE2]编译程序体积大的问题

    作者:cashfly 发布:2012-03-27 15:12 最近准备换Delphi高版本来写程序,以前一直用7.想体验一下新版本带来的便捷,首先有一个体积问题,看下文介绍. 首先,在IDE里可以直接 ...

  6. HTML 的 iframe 元素

    在 HTML 中, iframe 元素用于在网页中嵌入其它网页的内容,例如: <iframe src="http://example.com/abc.html">ifr ...

  7. 百度之星资格赛——Disk Schedule(双调旅行商问题)

    Disk Schedule Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) To ...

  8. redhat 6 配置 yum 源的两种方法

      由于 redhat的yum在线更新是收费的,如果没有注册的话不能使用,如果要使用,需将redhat的yum卸载后,重启安装,再配置其他源. 本文包括配置本地源及第三方源.第三方源包括:网易,epe ...

  9. 标准I/O库之临时文件

    ISO C标准I/O库提供了两个函数以帮助创建临时文件. #include <stdio.h> char *tmpnam( char *ptr ); 返回值:指向唯一路径名的指针 FILE ...

  10. 【转】C++里定义全局变量和函数常用方法

    http://blog.csdn.net/niying/article/details/637084 1:在头文件是声明变量,然后在使用的文件中用exten标识. ".h": in ...