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'
}

Object and Block Variables

Blocks provide support for Objective-C and C++ objects, and other blocks, as variables.

Blocks 对 OC 以及 C++ 对象提供支持,以及其它种类的 block 最为变量。

Objective-C Objects

When a block is copied, it creates strong references to object variables used within the block. If you use a block within the implementation of a method:

当一个 block copy了,它会对每个出如今 block 中的变量创建一个强引用。

假设你在一个方法的实现中使用了 block:

  • If you access an instance variable by reference, a strong reference is made to self; 假设你引用了一个实例变量。这会创建一个强引用指向 self

  • If you access an instance variable by value, a strong reference is made to the variable. 假设你引用了一个实例变量的值,这回创建一个对这个变量的强引用

The following examples illustrate the two different situations:

下面样例描写叙述了两种不同的情形:

dispatch_async(queue, ^{
    // instanceVariable is used by reference, a strong reference is made to self
    doSomethingWithObject(instanceVariable);
});
 
 
id localVariable = instanceVariable;
dispatch_async(queue, ^{
    /*
      localVariable is used by value, a strong reference is made to localVariable
      (and not to self).
    */
    doSomethingWithObject(localVariable);
});

To override this behavior for a particular object variable, you can mark it with the __block storage type modifier.

为了重写这样的表现形式,你能够给变量标记上 __block 存储方式。

Blocks

When you copy a block, any references to other blocks from within that block are copied if necessary—an entire tree may be copied (from the top). If you have block variables and you reference a block from within the block, that block
will be copied.

当你 copy 一个 block,不管参考其他 block 会是 copy。

将规划建设一个树状结构。假设你有 block 变数,和在里面 block 引用在此 block,那个 block 会是copy。

Blocks and Variables的更多相关文章

  1. [翻译] Blocks and Variables

    Blocks and Variables https://developer.apple.com/library/ios/documentation/cocoa/conceptual/Blocks/A ...

  2. Getting Started with Blocks

    本文来源为:developer.apple.com,仅仅是博主练习排版所用. Getting Started with Blocks The following sections help you t ...

  3. block的语法

    主要内容: 1. 开始使用block(Getting Started with Blocks) 2. block概念综述(Conceptual Overview) 3. 声明和创建block(Decl ...

  4. [转]50 Shades of Go: Traps, Gotchas, and Common Mistakes for New Golang Devs

    http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/ 50 Shades of Go: Traps, Gotc ...

  5. 最详细的block底层

    主要讲述的要点: block 干什么用的 block 语法 block 底层实现 block 变量捕捉 block 的种类.在存储空间中的存储位置 block 循环引用 __block 在ARC 中 ...

  6. (译)IOS block编程指南 2 block开始

    Getting Started with Blocks(开始block) The following sections help you to get started with blocks usin ...

  7. (译)IOS block编程指南 1 介绍

    Introduction(介绍) Block objects are a C-level syntactic and runtime feature. They are similar to stan ...

  8. Code::Blocks配置GTK+2和GTK+3

    Code::Blocks配置GTK+2和GTK+3 作者 He YiJun – storysnail<at>gmail.com 团队 ls 版权 转载请保留本声明! 本文档包含的原创代码根 ...

  9. ios理解 -- Pro Mutlithreading and Memory Management for iOS and OS X with ARC, Grand Central Dispatch, and Blocks

    Capturing automatic variables Next, you need to learn what the “together with automatic (local) vari ...

随机推荐

  1. or1200中IMMU分析(续)

    下面内容摘自<步步惊芯--软核处理器内部设计分析>一书 2 IMMU中的特殊寄存器 OR1200处理器中的IMMU包括第2组特殊寄存器,如表10.1所看到的. ITLBW0MRx是指令TL ...

  2. DocFX

    微软开源全新的文档生成工具DocFX 微软放弃Sandcastle有些年头了,微软最近开源了全新的文档生成工具DocFX,目前支持C#和VB,类似JSDoc或Sphinx,可以从源代码中提取注释生成文 ...

  3. hdu 4296 Buildings(贪婪)

    主题链接:http://acm.hdu.edu.cn/showproblem.php? pid=4296 Buildings Time Limit: 5000/2000 MS (Java/Others ...

  4. 江湖急救篇:slave 复制错误

    这样的事情是,我们DBA的一个暂时表,导致复制出错 老大给力,江湖救急. 关于该參数.淘宝丁奇写了篇文章还不错:MySQL小误区:关于set global sql_slave_skip_counter ...

  5. HDU 1864最大报销额(一维背包)

    题目地址:HDU 1864 刚上来看着挺麻烦的..细致看了看原来好简单好简单...仅仅要去掉一些不符合要求的发票,剩下的就是最简单的背包问题了..对于小数问题,仅仅要*100就变成整数了. 代码例如以 ...

  6. 算法 《霍纳的方法java实践》

    [历史背景] 霍纳的方法是中国南宋时期的数学家秦九韶表述求解一元高次多项式的值的算法--正负开方术. 它也能够配合牛顿法用来求解一元高次多项式的根.在西方被称作霍纳算法(Horner algorith ...

  7. sqlserver system object type

    select distinct s.type, s.type_desc from sys.objects as s inner join (select distinct type from sys. ...

  8. 提升Mac os x 10.10+xcode6.1之后,Cocoapods发生故障的解决方案

    提升Mac OS X 10.10+Xcode 6.1之后.Cocoapods图书馆管理也依赖于相应升级.现在最新的Release版本号是 0.34.在之前的版本号.当数据库更新和管理,你会遇到一个错误 ...

  9. DOM简要

    在看Js视频的时候就感觉Dom这东西太奇妙了.在这个注重用户体验的Web设计时代里.Dom是至关重要的. 它的易用性强.而且遍历简单.支持XPath. 它既然这么强大那么就来简单的介绍Dom这个东东. ...

  10. ffmpeg和opencv 播放视频文件和显示器

    ffmpeg它是基于最新版本,在官网下载http://ffmpeg.zeranoe.com/builds/.编译时VS2010配置相关头文件及库的路径就可以.opencv的搭建參考上一个博客. 首先简 ...