8

Assume

typedef void (^MyResponseHandler) (NSError *error);
@property (strong, nonatomic) MyResponseHandler ivarResponseHandler;
synthesize ivarResponseHandler = _ivarResponseHandler;

- (void)myMethod:(MyResponseHandler)responseHandler
{
    self.ivarResponseHandler = responseHandler;
    ...
}

Is the assignment to the ivar through the @property correct? I know that in manual memory management you would have needed self.ivarResponseHandler = [responseHandler copy]; to make sure the block was copied from the stack to the heap. But watching Session 322 - Objective-C Advancements in Depth (minute 25) from WWDC 2011, the speaker says that ARC automatically handles the assignment of a block to an ivar. I just wanted to make sure.

jscs
  • 63,694
  • 13
  • 151
  • 195
bearMountain
  • 3,950
  • 1
  • 36
  • 44

2 Answers2

11

ARC will automatically perform the copy for you in the code you posted.

If you convert the block to an id, ARC will not perform the copy for you. For example, in this code, ARC will not perform the copy because addObject:'s argument type is id:

NSMutableArray *array = [NSMutableArray array];
[array addObject:responseHandler];
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • Thanks a lot. Answered my question and more. – bearMountain May 02 '12 at 17:04
  • @adonoho Is it true that [the block is not automatically copied if assigned directly to an ivar](http://stackoverflow.com/questions/10453261/under-arc-are-blocks-automatically-copied-when-assigned-to-an-ivar-directly)? – bearMountain May 04 '12 at 17:14
  • bearMountain, I don't know what happens when it is assigned to an ivar. Frankly, I don't really want to depend upon what the compiler is going to do. I know that it is copied when assigned to a copy `@property`. I also know you can directly copy the block yourself on the assignment to the ivar. In both cases, there is no ambiguity. I prefer to always use `@property`s. Andrew – adonoho May 08 '12 at 15:13
2

bearMountain,

The easiest way to ensure the block is copied is to, in fact, set the @property to use copy. As in:

@property (copy, nonatomic) MyResponseHandler ivarResponseHandler;

It does everything you need.

Andrew

adonoho
  • 4,339
  • 1
  • 18
  • 22
  • Doesn't answer the question directly. But I think I'll use this pattern in my code now. – bearMountain Jun 06 '12 at 18:19
  • (two years later) I've just asked very similar question which answers yours: [Should I still copy/Block_copy the blocks under ARC?](http://stackoverflow.com/questions/23334863). General conclusion of the answer there is that the form for writing properties for blocks, this accepted answer here has, is absolutely right and correct form even in present days. – Stanislav Pankevich Apr 29 '14 at 07:34