WhiteTherewasproblem WhiteTherewasproblem - 4 months ago 8
Objective-C Question

Will the compiler automatically copy block property to heap?

Will the compiler automatically copy a block property to heap, no matter it's under 'Strong' or 'copy' attribute?

As some say it's a rule but they can't tell why, I'd like to know more details.

CRD CRD
Answer

In the latest version, Sept 2014, of Apple's Working with Blocks, they stated that block-valued properties should use copy, but then immediately come clean (emphasis added):

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.

So the answer to your question:

Will the compiler automatically copy a block property to heap, no matter it's under 'Strong' or 'copy' attribute?

is yes, so as long as you use ARC - which is standard these days.

As to "best practice" that is debatable: blocks are immutable objects, which you don't usually copy. The copy was only ever needed as Apple originally choose to make the block-on-the-stack optimisation both visible and partly programmer-supported - an unusual choice for a compiler optimisation. However for ARC users those days are long gone, however MRC users must still manually manage this optimisation.

HTH

Comments