Saving a block in an instance variable

How to declare a global (private instance variable) to accept a block in it. Do we need to synthesize it and what are the consequences of managing memory with it.

I have a block received from a third-party method that I want to store in an instance variable and use it at a later stage.

+3
source share
2 answers

Here's an example (ARC-less) of storing a block to complete 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
+12
source

Refer to Blocks Programming Topics:

You can copy and release blocks using C functions:

Block_copy();
Block_release();

Objective-C, copy, retain release ( autorelease).

, Block_copy() Block_release(). copy retain release ( autorelease) - .

+2

All Articles