Saving a block in instance variable

后端 未结 2 1971
时光取名叫无心
时光取名叫无心 2021-01-20 06:17

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.

相关标签:
2条回答
  • 2021-01-20 06:36

    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.

    0 讨论(0)
  • 2021-01-20 06:56

    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
    
    0 讨论(0)
提交回复
热议问题