将Objective-C块定义为属性 - 最佳实践 [英] Defining Objective-C blocks as properties - best practice

查看:97
本文介绍了将Objective-C块定义为属性 - 最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了一个 Apple文档显示块的以下属性声明:

I've recently come across an Apple document that shows the following property declaration for a block:

@interface XYZObject : NSObject
@property (copy) void (^blockProperty)(void);
@end

此外,本文还说明:


注意:您应该指定copy作为属性属性,因为需要复制块以跟踪其在原始范围之外的捕获状态。这不是您在使用自动引用计数时需要担心的事情,因为它会自动发生,但是属性属性的最佳实践是显示结果行为。有关更多信息,请参阅块编程主题。

Note: 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. For more information, see Blocks Programming Topics.

我还阅读了建议的阻止编程主题但没有找到任何相关内容。

I also read the suggested Blocks Programming Topics but haven't found anything relevant there.

我仍然很好奇为什么将块属性定义为copy是最佳做法。如果您有一个好的答案,请尝试区分ARC和MRC差异(如果有)。

I'm still curious as to why defining a block property as "copy" is best practice. If you have a good answer, please try to distinguish between ARC and MRC differences if there are any.

谢谢

推荐答案

默认情况下,会在堆栈上创建块。这意味着它们只存在于它们创建的范围内。

By default blocks are created on the stack. Meaning they only exist in the scope they have been created in.

如果您想稍后访问它们,则必须通过发送<$ c将它们复制到堆中$ c>复制消息到块对象。一旦检测到需要在其创建的作用域之外访问块,ARC将立即为您执行此操作。作为最佳实践,您将任何块属性声明为副本,因为这是它应该在自动内存管理下的方式。

In case you want to access them later they have to be copied to the heap by sending a copy message to the block object. ARC will do this for you as soon as it detects a block needs to be accessed outside the scope its created in. As a best practise you declare any block property as copy because that's the way it should be under automatic memory management.

阅读 Objective-C中的堆栈和堆对象,由Mike Ash提供有关堆栈与堆的更多信息。

Read Stack and Heap Objects in Objective-C by Mike Ash for more info on stack vs. heap.

这篇关于将Objective-C块定义为属性 - 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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