Block auto save, does it even affect Ivars?

If I have a class:

@interface A : NSObject { BOOL b; id c; } @end 

and references b and c in the block, is the self block saved automatically? Or just b and c ? About c it can persist by itself, but what about b ?

+4
source share
2 answers

The answer to the answer is not entirely correct:

If you have instance A and create a block inside that instance, for example:

 ^{ b = YES; } 

Then self saved (when copying a block). b not const -copied, because b strictly refers to self , and only self is const within the scope of the block.

On the other hand, if you do this:

 BOOL aBool = YES; ^{ aBool = NO; c = [[NSObject alloc] init]; } 

Then again self const -copied (and saved when the block itself is copied), and assignment c allowed. However, the assignment of aBOOL not valid because the value of aBOOL is const -copied.

In other words, the compiler recognizes that b and c are ivars, and store self instead of ipars directly.


One way to think about this, which helps me understand what is happening, is to remember that the object is really just a bizarre structure, which means that you can technically access ivars using the arrow operator: ->

So when you turn to ivars:

 b = YES; 

is equivalent to:

 self->b = YES; 

In this light, it is understandable why you need to keep self , but b not const . This is because b is only a thin part of the β€œlarger image”, and to get b you must include all self (since copying part of the structure does not really make sense in this context).

+9
source

The code from the block will be useful in answering, but on the condition that you have something like this:

 ^(A *a) { [a doSomething]; } 

a will be saved by the block and released when the block is released. Nothing unusual will happen with b and c .

If you have something like:

 ^(id c, BOOL b) { [c doSomethingElse]; } 

Then c will be saved by the block, and b will be fixed by the block as the value of const (i.e. you will get a compiler error to execute b = NO )

See the docs for more details;

http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/bxVariables.html%23//apple_ref/doc/uid/TP40007502-CH6-SW1

+1
source

All Articles