[cfe-dev] Compiler Warnings for Variables Retained by Block

Fabian milkservice at gmail.com
Wed Jan 29 23:28:01 PST 2014


Hi List,

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.

So I thought maybe another approach could be possible and helpful in a
potential future compiler version:
* A compiler setting to activate warnings for *all* strongly captured
objects in blocks
* A pragma or similar to deactivate the warning locally for a list of
objects

An example:

- (void)someMethod {
    NSArray *someArray1 = [NSArray array];
    NSArray *someArray2 = [NSArray array];
    self.someProperty.block = ^{
        NSLog(@"%@,%d,%@,%@",self,_instanceVariable,someArray1,someArray2);
    };
}

This code block would output a warning for `self`, `someArray1` and
`someArray2` being captured strongly in the block. To silence the warning:

- (void)someMethod {
    NSArray *someArray1 = [NSArray array];
    NSArray *someArray2 = [NSArray array];
    __weak typeof(self) weakSelf = self;
    self.someProperty.block = ^{
#pragma clang allow-capture-strongly(someArray1,someArray2)
        NSLog(@"%@,%d,%@,%@", weakSelf,
weakSelf->_instanceVariable,someArray1,someArray2);
    };
}

That way all strongly captured objects need to be approved.

What do you think? Would that make code more robust?

Yours,
Fabian
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20140130/0e927f00/attachment.html>


More information about the cfe-dev mailing list