objective c - Using __block and __weak -


i've read on thread: what "__block" keyword mean? discusses __block used i'm confused 1 of answers. says __block used avoid retain cycles, comments underneath leave me unsure.

i'm using this:

 self.someproperty = x; //where x object (id)  __block __weak vp_user *this = self;   //begin callback-style block      this.someproperty = nil; 

do need use both __block , __weak? glaring problems way looks?

__block storage qualifier. specifies variable should directly captured block opposed copying it. useful in case need modify original variable, in following example

__block nsstring *astring = @"hey!";  void(^ablock)() = ^{ astring = @"hello!" }; // without __block couldn't modify astring nslog(@"%@", astring); // hey! ablock(); nslog(@"%@", astring); // hello! 

in arc causes variable automatically retained, can safely referenced within block implementation. in previous example, then, astring sent retain message when captured in block context.

not doesn't hold true in mrc (manual reference counting) variable referenced without being retained.

marking __weak causes variable not retained, block directly refers without retaining it. potentially dangerous since in case block lives longer variable, since referring garbage memory (and crash).

here's relevant paragraph clang doc:

in objective-c , objective-c++ languages, allow __weak specifier __block variables of object type. [...] qualifier causes these variables kept without retain messages being sent. knowingly leads dangling pointers if block (or copy) outlives lifetime of object.

finally claim __block can used avoid strong reference cycles (aka retain cycles) plain wrong in arc context. due fact in arc __block causes variable referenced, it's more cause them.

for instance in mrc code breaks retain cycle

__block typeof(self) blockself = self; //this retain self in arc! [self methodthattakesablock:^ {     [blockself dosomething]; }]; 

whereas achieve same result in arc, do

__weak typeof(self) weakself = self; [self methodthattakesablock:^ {     [weakself dosomething]; }]; 

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -