简体   繁体   中英

Will self retain within block?

Before/After call the block, the retaincount is always 1. From apple block doc we know that the self should retain. Can anyone know why?

NSLog(@"Before block retain count: %d", [self retainCount]);    
void (^block)(void) = ^(void){
    UIImage* img = [UIImage imageNamed:@"hometown.png"];
    [self setImage:img];
    NSLog(@"After block retain count: %d", [self retainCount]);
};
block();

First, retainCount is useless. Don't call it. .

Blocks only retain captured objects when the block is copied. Thus, self won't be retained by the block in that example.

OK I did some research, now things became more clear. firstly, I didn't use @property on block1, which means when I set it, nothing is copied, so they are not retained, secondly, if we do a [block copy], the variables will be retained, if we dont copy, the block points to a stack address, copy it to heap to make it safe.

the variable 'array' is a Member variable, so it's not retained and meanwhile the self will be retained, whether you put it in the block or not, if the variable is a local variable, it will be retained. ( this is the thing that Im still confused abt, why the member variable is not retained,instead the self is added one more on retain count??? pls answer me?)

after using the block we could set it to nil self.block = nil; to make variables released, and avoid the retain cycle.

PS. a method to break retain cycle is use __block id weakSelf = self; in the block, so it means __block variables are also not retained.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM