0

Let's say we want to store SomeBlock

typedef void(^SomeBlock)(void);

in a private member variable of an object of type SomeClass in order to store it and run it later. We could do it this way:

//SomeClass.m

@implementation SomeClass{
    SomeBlock _someBlock;
}
//some code
@end

or we could do it this way:

//SomeClass.m
@interface SomeClass()
@property (nonatomic, copy) SomeBlock someBlock;
@end

According to http://goshdarnblocksyntax.com/, the latter is preferable. Why? Both examples are functional, but I wonder if there's some sort of memory implications I don't understand. There was some discussion around it in a non-ARC environment here: Saving a block in instance variable, but I am interested in using blocks as member variables in an ARC environment.

Community
  • 1
  • 1
AtomicBoolean
  • 1,070
  • 13
  • 19
  • 1
    `SomeBlock * _someBlock;` would not have the `*`. – Ian MacDonald Mar 12 '15 at 20:53
  • Where does that website say that the property is preferable? I just see syntax help. – jscs Mar 12 '15 at 20:53
  • It's just more modern to declare things as properties instead of declaring a bunch of ivars. – AdamPro13 Mar 12 '15 at 20:58
  • 1
    Closely related: [Blocks as strong pointers vs. copy](http://stackoverflow.com/q/27152580), [Defining ObjC blocks as properties best practice](http://stackoverflow.com/q/14649661), [What qualifier should I use to declare a block as an ivar?](http://stackoverflow.com/q/10128552) – jscs Mar 12 '15 at 21:01
  • 1
    (Although the second paragraph of my answer at that third link is wrong, I think.) – jscs Mar 12 '15 at 21:02
  • 1
    Thanks @JoshCaswell; you answered my question. Basically, you should be able to use the retained block just fine because ARC should handle it. But just in case they don't, it is a best practice to copy it to the heap, in the case that the block needs to outlive its lifetime in the stack. – AtomicBoolean Mar 12 '15 at 21:21

0 Answers0