See the following animation execution block, how does the UI control pointer clickButton copy from stack to heap? By reference (retain) or just copy pointer value (not deep copy)?
Thanks in advance.
[UIView animateWithDuration:10.0 animations:^(void){
clickButton.alpha = 1.0; // clickButton is class variable.
}];
When a block is copied (which it is in this case), any objective-c objects that are referenced by the block are retained (and then released when the block is dealloc’d).
In this case, if
clickButtonwas a local variable outside the block, it would be retained inside the block. However, you said it was a “class variable”, which I assume you mean it’s an instance variable. Because of that, the block actually retainsself, since the reference to the ivar is really an implicit lookup of the ivar withinself.In MRR (non-ARC) code, any obj-c objects which are marked with the
__blockstorage qualifier are actually not retained by the capturing block. This is for technical reasons, but it has been taken advantage of by many people. However, in ARC code,__block-qualified variables do get retained (and released) by the block. If you need a non-retained object under ARC, you can use__unsafe_unretainedinstead. However, in ARC code, weak references typically solve the same problem that__unsafe_unretainedvariables do, but much more safely.Since the block here has a temporary lifetime (it only lives for the duration of the animation), there’s no problem with retaining self. However, for more permanent blocks whose lifetime are actually tied to that of
self(e.g. they’re stored in an ivar, or on an object thatselfowns), you should be careful not to introduce a retain cycle. If you’re using ARC, weak references can help you here.