<div dir="ltr">Hi List,<div><br></div><div>lately I've been working with ObjC Blocks a lot, and often longed for more compiler support regarding warnings for strongly captured objects. Analyzing gives some warnings for capturing `self` strongly in a block, but it doesn't catch all cases, and sometimes capturing other objects can also lead to retain cycles.</div>
<div><br></div><div>So I thought maybe another approach could be possible and helpful in a potential future compiler version:</div><div>* A compiler setting to activate warnings for *all* strongly captured objects in blocks</div>
<div>* A pragma or similar to deactivate the warning locally for a list of objects</div><div><br></div><div>An example:</div><div><br></div><div>- (void)someMethod {</div><div> NSArray *someArray1 = [NSArray array];<br>
</div><div> NSArray *someArray2 = [NSArray array];<br></div><div> self.someProperty.block = ^{<br></div><div> NSLog(@"%@,%d,%@,%@",self,_instanceVariable,someArray1,someArray2);</div><div> };</div>
<div>}</div><div><br></div><div>This code block would output a warning for `self`, `someArray1` and `someArray2` being captured strongly in the block. To silence the warning:</div><div><br></div><div><div>- (void)someMethod {</div>
<div> NSArray *someArray1 = [NSArray array];<br></div><div> NSArray *someArray2 = [NSArray array];<br></div><div> __weak typeof(self) weakSelf = self;<br></div><div> self.someProperty.block = ^{</div><div>#pragma clang allow-capture-strongly(someArray1,someArray2)</div>
<div> NSLog(@"%@,%d,%@,%@", weakSelf, weakSelf->_instanceVariable,someArray1,someArray2);</div><div> };<br></div><div>}</div></div><div><br></div><div>That way all strongly captured objects need to be approved.</div>
<div><br></div><div>What do you think? Would that make code more robust?</div><div><br></div><div>Yours,</div><div>Fabian</div>
</div>