[翻译] Blocks and Variables

Blocks and Variables

https://developer.apple.com/library/ios/documentation/cocoa/conceptual/Blocks/Articles/bxVariables.html

http://stackoverflow.com/questions/16149653/what-is-the-role-of-the-copy-in-the-arc

 

This article describes the interaction between blocks and variables, including memory management.

这篇文章描述了 blocks 与变量间的交互作用,同时也包括内存管理。

 

Types of Variable

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

在 block 对象体中插入的代码,变量可以分为5种。

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

你可以引用 3 种标准类型的变量,就像你在普通方法中使用的那样子:

  • Global variables, including static locals  全局变量,包括 static 修饰过的静态变量
  • Global functions (which aren’t technically variables) 全局方法(技术上来说不能被称作变量)
  • Local variables and parameters from an enclosing scope 局部变量和从上下文中带进来的参数

Blocks also support two other types of variable:

Blocks 也支持另外两种类型的变量:

  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 修饰的对象。它在block里面是可以修改的,如果这个 block 被 copy 到了栈区,这个对象就会被强引用。
  2. const imports. const引入的。

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

最终,在一个方法的实现当中,blocks 也许会强引用 Objective-C 实例变量,请参考  “Object and Block Variables.” 

The following rules apply to variables used within a block:

以下规则适用于在 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). 传递到 block 中的变量(就像函数传递参数一样)
  3. Stack (non-static) variables local to the enclosing lexical scope are captured as const variables. 相对于 block 块的非静态堆区对象被识别为 const 对象。

    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.  他们的值会以指针的形式传递到 block 中。

  4. Variables local to the enclosing lexical scope declared with the __block storage modifier are provided by reference and so are mutable.  __block 修饰的对象允许在 block 中进行修改,并会被 block 强引用。

    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. 在 block 块中实例化的对象,与在函数中实例化的对象基本一致。

    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. 每一次调用这个 block 都会提供一个变量的 copy。相应的,这些对象可以被当做 const 或者是强引用的对象使用。

The following example illustrates the use of local non-static variables:

以下例子描述了如何使用一个本地非 static 的变量:

int x = 123;
 
void (^printXAndY)(int) = ^(int y) {
 
    printf("%d %d\n", x, y);
};
 
printXAndY(456); // prints: 123 456

As noted, trying to assign a new value to x within the block would result in an error:

正如提到的那样,给 x 在 block 中直接赋值会引发错误:

int x = 123;
 
void (^printXAndY)(int) = ^(int y) {
 
    x = x + y; // error
    printf("%d %d\n", x, y);
};

To allow a variable to be changed within a block, you use the __block storage type modifier—see “The __block Storage Type.”

为了允许一个变量在 block 中可以被修改,你需要使用 __block 存储的类型,查看 “The __block Storage Type.”

 

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 registerauto, and static storage types for local variables.

你可以指定引入的对象可以被修改,那就是,可读可写。通过给这个变量修饰 __block 存储修改类型。__block 存储与 register ,auto,static 存储方式互斥(对于一个别修饰的变量)。

__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.

__block 变量在一个容器中存活,可以被变量的上下文共享,可以被所有 block 共享,可以被 copy 修饰过的 block 共享,以及在 block 块中创建的对象共享。也就是说,如果有任何 copy 出来的 block 用了这个变量,它会一直存活于堆区当中。

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 存储开始与堆区,就像 blocks 他们自己做的那样子。如果这个 block 被 copy 了(或者在 OC 当中 block 接收到了 copy 消息)。变量就会被复制到栈区去。也就是说,这个变量可以一直被修改了。

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中可变长度数组的结构体。

The following example illustrates use of a __block variable:

以下例子描述了怎么使用 __block 变量:

__block int x = 123; //  x lives in block storage
 
void (^printXAndY)(int) = ^(int y) {
 
    x = x + y;
    printf("%d %d\n", x, y);
};
printXAndY(456); // prints: 579 456
// x is now 579

The following example shows the interaction of blocks with several types of variables:

以下例子显示了 blocks 如何与不同类型的变量交互:

extern NSInteger CounterGlobal;
static NSInteger CounterStatic;
 
{
    NSInteger localCounter = 42;
    __block char localCharacter;
 
    void (^aBlock)(void) = ^(void) {
        ++CounterGlobal;
        ++CounterStatic;
        CounterGlobal = localCounter; // localCounter fixed at block creation
        localCharacter = 'a'; // sets localCharacter in enclosing scope
    };
 
    ++localCounter; // unseen by the block
    localCharacter = 'b';
 
    aBlock(); // execute the block
    // localCharacter now 'a'
}
时间: 2024-10-25 20:02:06

[翻译] Blocks and Variables的相关文章

[转]GNU Radio Companion - GRC

GNU Radio Companion - GRC 注:该文档适应于捆绑 GNU Radio 的 GRC,它不适应任何独立发行本的 GRC.如果想使用 GRC 0.70 请参阅 GNU Radio Companion (Old) . GNU Radio Companion (GRC) 是一个用来产生信号流程图及流程图源代码的图形化工具.它目前是由 Josh Blum 构建.   新特性  同稳定版 GRC 0.70 不同的,GRC 目前有哪些新特性? 捆绑式发行(Bundled)- GRC 目前

Whats New in PHP 5 countstars(翻译)

翻译:深空 作者:Andi Gutmans, Stig Bakken, and Derick Rethans 不得擅自转载. Introduction [绪论] Language Features [语言特性] • New Object Oriented model [新的面向对象模型] • New Object Oriented Features [新的面向对象特性] • Other New Language Features [其他新的语言特性] General PHP changes [P

Java Thread Programming 1.7 - Concurrent Access to Objects and Variables

access|object When multiple threads are interacting with an object, controls need to be in place to ensure that the threads don't adversely affect one another. This chapter deals with issues that can introduce subtle errors in your application. An ap

不知道大家对DES有没有兴趣,今天在整理的时候,看到我在一年半前翻译的一篇文章。

如何实现 DES 算法(全). 这是摘自清华BBS的一篇文章,洋文的,小弟把它翻成中文请各位高手指点.分号(:)后的话是小弟的翻译,井号(#)后的是小弟的一点感想.                           How to implement the                      Data Encryption Standard (DES)                         A step by step tutorial                     

>第六章 控制语句(rainbow 翻译)(来自重粒子空间)

控制|语句 <<展现C#>>第六章 控制语句(rainbow 翻译)  出处:http://www.informit.com/matter/ser0000002 正文:                                  第六章   控制语句     有一种语句,你在每种编程语言控制流程语句中都可以找到.在这一章中,我介绍了C#的控制语句,它们分为两个主要部分:.选择语句.循环语句如果你是C或C++程序员,很多信息会让你感到似曾相似:但是,你必须知道它们还存在着一些差

c#v2.0 扩展特性 翻译(1)

Introduction to C# 2.0C# 2.0 introduces several language extensions, the most important of which are Generics, Anonymous Methods, Iterators, and Partial Types. C#2.0 介绍几种语言扩展,泛型,匿名方法,迭代器 和.partial Types. · Generics permit classes, structs, interfaces

[翻译]:SQL死锁-阻塞探测

原文:[翻译]:SQL死锁-阻塞探测 到了这篇,才是真正动手解决问题的时候,有了死锁之后就要分析死锁的原因,具体就是需要定位到具体的SQL语句上.那么如何发现产生死锁的问题本质呢?下面这篇讲的非常细了,还提到了不少实用的SQL,但对我个人来讲,前半部分基本就够用,可以指出死锁的原因,至于后面那些有兴趣可以多研究研究. As we already know, usually blocking happens due non-optimized queries. But how to detect

在Code::Blocks试用与安装vim插件

博主一直都是在Linux下做开发,平时用的编辑器都是VIM.可vim这的痛点是插对C++的补全做不够好.我想要的是当我输入string::时就能提示string下的方法. 无意间博主看到了Code::Blocks,于是安装上来玩玩.结果一玩就根本停不下来. 如下为Code::Blocks的主界面: 它各种鲜明的高亮一下子就征服了博主.主要是对C++的支持相当好.最令博主喜爱的是它的自动调整代码格式的功能,一点就能将整个工程的代码按照指定的格式进行调整. 但是,博主还是有点不习惯.没有vim风格的

使用GRC Any Blocks

GRC Any Blocks 当添加Any_Blocks到GRC后,无需自己写XML文件即可在GRC中调用python模块.下载Any_Blocks后,把几个XML文件拷到~/.grc_gnuradio文件夹,重新打开GRC即可调用这几个模块. Reason  To enable arbitrary Python-wrapped GNU Radio blocks to be created and connected in the flow graph code generated by GNU