6
__weak MyClass *selfReference = self;

dispatch_async(dispatch_get_main_queue(), ^{
        [selfReference performSomeAction];
    });
  • When do you need to pass a weak reference to a block?
  • Does this rule apply to dispatch_async as well as custom blocks?
  • Does a block copy the iVars used in it or does it retain them?
  • Who owns the variables initialized inside a block? Who should release them?
5
  • 2
    These questions are all answered in Apple's documentation. Aug 31, 2012 at 15:53
  • 1
    @JonathanGrynspan You could maybe give a pointer to the documentation?
    – mathk
    Aug 31, 2012 at 15:58
  • @JonathanGrynspan developer.apple.com/library/ios/#documentation/cocoa/Conceptual/… Here is a link to the documentation, but it doesn't answer my questions
    – aryaxt
    Aug 31, 2012 at 16:00
  • @aryaxt: Keep reading. It's all there. :) Aug 31, 2012 at 16:05
  • 1
    @Jonathan Grynspan Note that the referenced document does not have any mention of ARC yet several things about blocks WRT ARC--like __block now creating a strong reference, have changed.
    – zaph
    May 3, 2013 at 23:11

1 Answer 1

13

1, 2) Blocks retain the object-pointers in it (any blocks, dispatch_async blocks are nothing special). This usually isn't a problem, but can lead to retain-cycles, because the block can be associated with an owner object and that owner object (often self) might be retained by the block. In that case you should use a weak variable and then reassign it to a strong capture:

__weak MyClass *weakSelf = self;
self.block = ^{
    MyClass *strongSelf = weakSelf;
    ...
    [strongSelf ...];
    [strongSelf.property ...];
    [strongSelf->iVar ...];
 }

Note: If you access an iVar directly, the compiler will transform that into self->iVar and thus retains self!

3) Blocks only retain the pointers, they don't copy them.

4) Variables created inside a block belong to that block and will be released when that block goes out of scope.

3
  • Fabian, can you please comment on why you need to reassign to a strong pointer?
    – x89a10
    Feb 27, 2013 at 2:04
  • 1
    If you don't create a strong property 1) the compiler forbids the use of the -> operator and you can't access iVars and 2) the weak variable might be released while the block is executing. In order to make sure that the variable is not released while the block is executing, you'll have to assign it to a strong variable before using it. Feb 27, 2013 at 7:47
  • The question was specific to dispatch_async but that is not addressed in the answer.
    – zaph
    Sep 6, 2013 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.