Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under ARC, are Blocks automatically copied when assigned to an ivar via the property?

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.

like image 538
bearMountain Avatar asked May 02 '12 16:05

bearMountain


2 Answers

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];
like image 193
rob mayoff Avatar answered Nov 10 '22 09:11

rob mayoff


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

like image 35
adonoho Avatar answered Nov 10 '22 10:11

adonoho