Saving a block in instance variable

最后都变了- 提交于 2019-12-01 22:14:11

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!