是否仍应在ARC下复制/Block_copy块? [英] Should I still copy/Block_copy the blocks under ARC?

查看:109
本文介绍了是否仍应在ARC下复制/Block_copy块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚偶然发现了以下SO主题:为什么我们应该复制块而不是保留块?以下句子:

I've just stumbled over the following SO topic: Why should we copy blocks rather than retain? which has the following sentence:

但是,从iOS 6开始,它们被视为常规对象,因此您不必担心.

However, as of iOS 6 they are treated as regular objects so you don't need to worry.

我真的对这个断言感到困惑,这就是为什么我要问:这个断言是否真的暗示着Objective-C开发人员不需要

I was really confused by this assertion that is why I am asking: does this assertion really imply that Objective-C developers do not need to

@property (copy) blockProperties

[^(...){...) {} copy]

将堆栈及其内容从堆栈复制到堆了吗?

to copy blocks and their contents from stack to heap anymore?

我希望我所做的描述清楚.

I hope the description I've made is clear.

请,请冗长.

类似问题

在ARC下,是块直接分配给ivar时是否自动复制?.

推荐答案

ARC将自动复制该块.从clang的 Objective-C自动引用计数文档:

ARC will copy the block automatically. From clang's Objective-C Automatic Reference Counting documentation:

除了保留是在初始化__strong参数变量或读取__weak变量的一部分时完成的,每当这些语义要求保留块指针类型的值时,它都会产生Block_copy的效果. .当优化程序发现结果仅用作调用的参数时,它可能会删除此类副本.

With the exception of retains done as part of initializing a __strong parameter variable or reading a __weak variable, whenever these semantics call for retaining a value of block-pointer type, it has the effect of a Block_copy. The optimizer may remove such copies when it sees that the result is used only as an argument to a call.

因此,仅用作函数或方法调用参数的块可能仍是堆栈块,但其他任何ARC保留该块的地方都将复制该块.这是通过编译器发出对objc_retainBlock()(实现)的调用来实现的.为此:

So blocks used only as arguments to function or method calls may remain stack blocks, but otherwise anywhere that ARC retains the block it will copy the block. This is implemented by the compiler emitting a call to objc_retainBlock(), the implementation for which is:

id objc_retainBlock(id x) {
    return (id)_Block_copy(x);
}

将块属性声明为具有复制语义仍然是一个好主意,因为分配给强属性的块实际上将被复制.苹果推荐这个:

It is still a good idea to declare block properties as having copy semantics since a block assigned to a strong property will in fact be copied. Apple recommends this as well:

您应该将copy指定为属性属性,因为需要复制一个块以跟踪其在原始范围之外的捕获状态.使用自动引用计数时,您不必担心这件事,因为它会自动发生,但最好的做法是让property属性显示结果行为.

You should specify copy as the property attribute, because a block needs to be copied to keep track of its captured state outside of the original scope. This isn’t something you need to worry about when using Automatic Reference Counting, as it will happen automatically, but it’s best practice for the property attribute to show the resultant behavior.

请注意,由于此保留复制功能是由ARC提供的,因此它仅取决于ARC或ARCLite的可用性,不需要其他操作系统版本或OS_OBJECT_USE_OBJC.

Note that since this copy-on-retain feature is provided by ARC it is dependent only on ARC or ARCLite availability and does not otherwise require a particular OS version or OS_OBJECT_USE_OBJC.

这篇关于是否仍应在ARC下复制/Block_copy块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆