Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

block_copy when to use

When to copy a block? The document says, blocks are "deleted when execution returns from the scope in which they are defined.This means you can’t return them directly from a function. If blocks could only be used while their defining scope was still on the call stack, they wouldn’t be nearly as useful as they actually are"

So, here is code which I tried, hoping the block will be deleted once execution is completed in viewDidLoad.

MyReaderController.h

@interface MyReaderController : UIViewController
{
    myBlockVar aBlockVar;
}
-(myBlockVar) getABlock;
@end

MyReaderController.m

@implementation MyReaderController
- (void)viewDidLoad
{
    [super viewDidLoad];
    aBlockVar=[self getABlock];
    NSLog(@"Block Result = %f",aBlockVar(1));
}
-(void) viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    NSLog(@"Block Exists even after the execution completes=%@ %f",aBlockVar,aBlockVar(5));
}

-(myBlockVar) getABlock{
    return ^(int var){return 4.0f;};
}

@end

So, does this code require viewDidLoad to be changed to as coded below, if not then when should I use it.

- (void) viewDidLoad{
    [super viewDidLoad];
    aBlockVar=Block_copy([self getABlock]);
    NSLog(@"Block Result = %f",aBlockVar(1));
}

PART 2

Later on I tried with this following code, hoping now it will return aBlockVar as nil obj in viewDidDisappear.

- (void)viewDidLoad
{
    [super viewDidLoad];
    Blocker *blocker=[[Blocker alloc] init];
    myBlockVar myVar=[blocker getABlock];
    aBlockVar=myVar;
    NSLog(@"Block Result = %f",aBlockVar(1));
    blocker=nil;
    myVar=nil;
}

Blocker.m

#import "Blocker.h"

@implementation Blocker

-(myBlockVar) getABlock{
    return ^(int var){return 4.0f;};
}
@end
like image 484
weber67 Avatar asked Dec 27 '22 08:12

weber67


2 Answers

Are you using ARC? If so, you don't need to use Block_copy or Block_release.

If you are, then you are correct with your revised code, as Block_copy takes it off the stack and into the heap where it is has an effective retain count of 1. You would also need to call Block_release where appropriate, when finally finished with the block, to bring its balance the copy, effectively bringing the retain count back to 0.

like image 195
Benjamin Mayo Avatar answered Jan 15 '23 07:01

Benjamin Mayo


use @property (nonatomic, copy) (int)(^myBlock)(void);

let the system do all right memory management for you!

initialize:

self.myBlock = ^int(void){
    return 4.0;
};

if you want to destroy your block somewhere do self.myBlock = NULL;

like image 21
iiFreeman Avatar answered Jan 15 '23 06:01

iiFreeman