Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy property and Block_copy(myBlock) / [myBlock copy]

Consider:

typedef void (^select_block_t)(UIView *) ;

(1) @property (copy, nonatomic) select_block_t        myBlockProperty ;
(2) @property (strong, nonatomic) select_block_t      myBlockProperty ;
(3) @property (assign, nonatomic) select_block_t      myBlockProperty ;

and:

(A) self.myBlockProperty = ^(UIView *) {NSLog(@"Hi");} ;
(B) self.myBlockProperty = [^(UIView *) {NSLog(@"Hi");} copy] ;

I am trying to understand what is the correct way to map which property declaration with which block copy semantics

I have seen examples here on S.O. that would favor[1:B]

But then I get confused by how redundant the 'copy' operation is. My limited understanding is that [1:A] should be correct, because I want the block to be copied once when I assign the property, not once at block creation and then once again at property assignment time.

[3:B] would also make sense according to my rationale. So, what am I misunderstanding?

like image 540
verec Avatar asked Apr 09 '12 16:04

verec


1 Answers

[1:A] is correct, yes. [3:B] is incorrect because:

  1. it's not clear that the class owns the property, so should release it in dealloc (but it should)
  2. the setter (B) looks like a leak, and the static analyser might flag it as such, because the block is copied, handed to a property, then leaves the scope with retain count +1.
  3. using (3) means that it only works if you set a heap-block (a copied block) with a retain count of one. This leaves plenty of margin for error when using the property. (1) works with both stack-blocks and heap-blocks, and will also correctly retain auto-released blocks.

EDIT: I see you're using ARC. In that case, it's not possible to use [3:B] at all. The compiler will release an object (even when copyed) once it's out of scope, and this property setter won't have retained it. Therefore the property will contain a bad pointer, it's an EXC_BAD_ACCESS waiting to happen.

like image 176
joerick Avatar answered Oct 23 '22 08:10

joerick