问题
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