[LLVMbugs] [Bug 10546] New: Block capturing self with __weak in ARC

bugzilla-daemon at llvm.org bugzilla-daemon at llvm.org
Sun Jul 31 20:56:36 PDT 2011


http://llvm.org/bugs/show_bug.cgi?id=10546

           Summary: Block capturing self with __weak in ARC
           Product: clang
           Version: trunk
          Platform: All
        OS/Version: All
            Status: NEW
          Severity: enhancement
          Priority: P
         Component: -New Bugs
        AssignedTo: unassignedclangbugs at nondot.org
        ReportedBy: remy.demarest at gmail.com
                CC: llvmbugs at cs.uiuc.edu


I would like to know if it's possible to add a feature to the blocks to allow
capturing variables in a weak manner inside blocks (especially self) to avoid
weak references.

Currently, the recommendation to capture self in a block is this (example with
NSNotification):

__weak MyClass *weakSelf = self;

[[NSNotificationCenter defaultCenter]
addObserverForName:NSApplicationDidResignActiveNotification object:nil
queue:nil usingBlock:
 ^(NSNotification *note)
 {
     __strong MyClass *fakeSelf = weakSelf;

     if(fakeSelf != nil)
     {
         fakeSelf->someIvar = value;
     }
 }];

This is incredibly verbose and repetitive for something that can be quite
common.

I propose to introduce a syntax allowing the developer to import self in a weak
manner, and have it converted to a strong object in the block directly.
Something along these lines:

[[NSNotificationCenter defaultCenter]
addObserverForName:NSApplicationDidResignActiveNotification object:nil
queue:nil usingBlock:
 ^(NSNotification *note)
 { | __weak self | // Finding a new use to an old syntax

     if(self != nil)
     {
         // it's not necessary to explicitly put self-> to affect that variable
         someIvar = value;
     }
 }];

What this syntax means is that self is captured weakly by the block, when the
block is executed, the block loads the weak self into a local strong variable
thus retaining self for the time the block is executing, and releasing it at
the end of the execution (or when the compiler thinks it's necessary).
The behaviour of that construction is exactly the same as the one in the
previous syntax, and remains also pretty explicit, but it reduces the code for
the whole capture.

-- 
Configure bugmail: http://llvm.org/bugs/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
You are on the CC list for the bug.



More information about the llvm-bugs mailing list