Block Retain Cycles

Blocks have retain counts. If you have retain counts, you can get retain cycles. Here is a typedef for a simple block, and a class that references the block, along with a string instance variable.

t​y​p​e​d​e​f​ ​v​o​i​d​ ​(​^​B​o​r​i​n​g​B​l​o​c​k​)​(​v​o​i​d​)​;​

/​/​ ​T​h​e​ ​l​e​a​k​y​ ​o​b​j​e​c​t​.​
@​i​n​t​e​r​f​a​c​e​ ​L​e​a​k​z​o​r​ ​:​ ​N​S​O​b​j​e​c​t​ ​{​
 ​ ​ ​ ​N​S​S​t​r​i​n​g​ ​*​_​s​t​r​i​n​g​;​
 ​ ​ ​ ​B​o​r​i​n​g​B​l​o​c​k​ ​_​b​l​o​c​k​h​e​a​d​;​
}​

/​/​ ​P​r​i​n​t​ ​|​s​t​r​i​n​g​|​.​
-​ ​(​v​o​i​d​)​ ​f​u​n​k​;​

@​e​n​d​ ​/​/​ ​L​e​a​k​z​o​r​

And here are -init and -dealloc.

-​ ​(​i​d​)​ ​i​n​i​t​ ​{​ ​ ​ ​ ​i​f​ ​(​(​s​e​l​f​ ​=​ ​[​s​u​p​e​r​ ​i​n​i​t​]​)​)​ ​{​ ​ ​ ​ ​ ​ ​ ​ ​_​s​t​r​i​n​g​ ​=​ ​@​"​s​n​o​r​k​"​;​ ...

Get Advanced Mac OS X Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.