[翻译] 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 register, auto, 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'
}
目录
相关文章
|
5天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
6444 14
|
5天前
|
弹性计算 人工智能 API
Codex超详细入门指南(下载·安装·登录·上手,全版本覆盖,2026最新版)
建议收藏本教程,2026 全年各版本更新随时回来查阅。如果你在搭建过程中遇到任何问题,欢迎结合 阿里云工单系统 提交技术支持请求,或在 阿里云开发者社区 搜索 Codex 相关话题交流。 祝你编码愉快,效率翻倍!
2262 8
|
8天前
|
人工智能 前端开发 API
阿里云Qwen4-Max 大模型详解:定位、特征、能力、适用场景与相对Qwen3-Max差异解析
2026年11月11日,阿里发布第四代旗舰模型Qwen4-Max预览版,首发千问AI平台Token Plan并接入千问办公、Qoder等入口。该版本聚焦知识理解、世界感知、编程与Agentic四项升级,主打复杂编程、专业办公、前端设计与专业软件操作等真实任务。预览期为11月11日10:00至11月25日24:00,仅支持Token Plan调用,到期后模型标识下线;限时2折、新用户再享5折,最低1折可体验。
|
8天前
|
JSON 前端开发 API
阿里云最新Qwen4-Max大模型介绍:模型定位、特征、能力、适用场景解析
2026 年 11 月 11 日,阿里发布第四代旗舰模型Qwen4-Max预览版,首发千问 AI 平台 Token Plan,并同步接入千问办公、Qoder 等入口。该版本聚焦知识理解、世界感知、编程与 Agentic 四项升级,主打复杂编程、专业办公、前端设计与专业软件操作。预览期至 11 月 25 日 24:00,到期后模型标识下线;限时 2 折、新用户再享 5 折,最低 1 折可体验。
|
3天前
|
传感器 安全 区块链
Windows 电脑运行安卓应用教程:开源工具 ApkStart 双击 APK 即装、独立窗口运行
ApkStart 是一款开源Windows工具,让安卓APP像原生软件一样运行:双击APK即安装、生成真实图标、独立窗口启动、开始菜单可搜索。无需传统模拟器,内置QEMU运行时,支持数据互通、ARM兼容与命令行操作。(239字)
|
21天前
|
Linux 开发工具 iOS开发
Codex保姆级教程(下载+安装+登录+使用,含所有版本,2026最新)
Codex是OpenAI推出的开源AI编程智能体,本地运行,可理解整个代码库,支持自然语言指令改代码、执行命令、跑测试、修Bug,兼容Win/macOS/Linux。(239字)
10091 59
|
4天前
|
人工智能 弹性计算 开发工具
零成本玩各大模型!DeepSeek Harness dsh-our-free-model 插件,13 个厂商模型直接用
总结一下:装这个插件,你不用注册、不用绑卡、不用填一个 Key,就能在 DeepSeek Harness 里用上 DeepSeek V4.1 Flash、Kimi K3 这一批前沿模型,而且是白嫖的、还不限量。三步搞定:下载插件,复制包含 `package.json` 的插件目录路径,在「添加插件」里粘贴路径安装并重启。无论是在阿里云 ECS 上通过命令行部署的 Web 版,还是本地的 Electron 桌面端,都能顺利跑通,快速搭建一套零成本的免费模型使用环境。
1026 0
|
6天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是DeepSeek AI开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、跑命令、处理表格、联网搜索等操作。免费开源,兼容Windows/macOS/Linux,提供桌面端与网页端,可灵活安装插件扩展能力。
|
15天前
|
Linux 开发工具 iOS开发
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
本文详解OpenAI Codex国内快速上手指南:提供Win/macOS/Linux全平台免安装包、npm/Homebrew等多方式安装、账号/API Key双登录、简体中文切换,覆盖下载、安装、汉化、使用及高频避坑(如微软商店失败、npm超时等),10分钟即可跑通。
3444 9