3

How do we declare a global(private instance variable) to accept a block in it. Do we need to synthesis it & what are the memory management implications with it.

I have a block received from a third party method which I want to save in the instance variable & use it at a later stage.

Abhinav
  • 37,684
  • 43
  • 191
  • 309

2 Answers2

12

Here's an (ARC-less) example of storing a block for a completion callback after doing some work in the background:

Worker.h:

@interface Worker : NSObject
{
    void (^completion)(void);
}
@property(nonatomic,copy) void (^completion)(void);
- (void)workInBackground;
@end

Worker.m:

@implementation Worker
@synthesize completion;

- (void)dealloc
{
    Block_release(completion);

    [super dealloc];
}

- (void)setCompletion:(void (^)(void))block
{
    if ( completion != NULL )
        Block_release(completion);

    completion = Block_copy(block);
}

- (void)workInBackground
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
    {
        // Do work..

        dispatch_async(dispatch_get_main_queue(), completion);
    });
}

@end
davehayden
  • 3,484
  • 21
  • 28
2

Please refer to Blocks Programming Topics:

You can copy and release blocks using C functions:

Block_copy();
Block_release();

If you are using Objective-C, you can send a block copy, retain, and release (and autorelease) messages.

To avoid a memory leak, you must always balance a Block_copy() with Block_release(). You must balance copy or retain with release (or autorelease)—unless in a garbage-collected environment.

Hailei
  • 42,163
  • 6
  • 44
  • 69
  • This is fine. Within the same controller class I want to save the block received in one method so that I could use it later in another method. How should I do that. I thought of saving block on some instance variable & then use it later. – Abhinav Apr 27 '12 at 02:17
  • You can't use `retain`, `release` or `autorelease` in an ARC environment either. – Abizern Apr 27 '12 at 02:23
  • See http://stackoverflow.com/questions/8360998/beginsheet-block-alternative-with-arc and http://stackoverflow.com/questions/9701923/arc-bridge-cast-block-copy-block-release if you are using ARC. – Hailei Apr 27 '12 at 02:48