Will self retain within block?

末鹿安然 提交于 2019-12-22 17:58:59

问题


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();

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/8502520/will-self-retain-within-block

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