__block的两种核心用法(摘自iOS 7 Programming Fundamentals: Objective-C, Xcode, and Cocoa Basics)

本文详细介绍了Objective-C中Block的使用方式,特别是__block修饰符的应用场景。通过具体的例子,展示了如何让Block捕获并使用定义时刻的变量值而非执行时刻的值,这对于处理异步任务和后台任务非常有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

page 69 - 73

1. 在block使用的区域里操作block之外的变量。

2. 

The second chief use of the__blockqualifier is the converse of the first. It arises when a block will be executed at some time after it is defined, and we want the block to use the value that a variable has at the time the block is executed, rather than capturing the value that it has when the block is defined. Typically this is because the very same method call that accepts the block (for later execution) also sets the value of this variable (now). 

这种用法是为了在block定义之后被调用而用的,同时我们想让该block被执行时使用这个变量,而不是在block被定义时获取这个变量。特别是当使用同一个方法调用这个block(之后执行)与设置这个变量(当前)。

For example, the methodbeginBackgroundTaskWithExpirationHandler:takes a block to be executed at some future time (if ever). It also generates and returns aUIBackgroundTaskIdentifier, which is really just an integer — and we are going to want to use that integer inside the block, if and when the block is executed. So we’retrying to do things in an oddly circular order: the block is handed as an argument tothe method, the method is called, the method returns a value, and the block uses thatvalue. The __blockqualifier makes this possible: 

__block UIBackgroundTaskIdentifier bti =
        [[UIApplication sharedApplication]
            beginBackgroundTaskWithExpirationHandler: ^{
                [[UIApplication sharedApplication] endBackgroundTask:bti];
}];

这个循环很有意思,对吧 :)


PS: 

1. block最明显的使用是在GCD中

2. 可以以使用static变量声明作为全局变量作为__block的代替,和__block的使用是一样的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值