0

I am using dispatch_async method to execute task in main queue. But it causing retain cycle:

Following is the code snippet:

self.test = ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"%@", self);
        });
   };

I am not able to get properly why it is creating retain cycle. As My controller does not have ownership of dispatch_async block.

1
  • 1
    Property test retains the closure and the closure contains a reference to self It doesn't matter that that reference is itself in a block Commented May 16, 2017 at 12:32

2 Answers 2

1

Try using weakSelf:

__weak typeof(self) weakSelf = self;

self.test = ^{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"%@", weakSelf);
    });
};
Sign up to request clarification or add additional context in comments.

1 Comment

but then self could get deallocated between the running of the outer block and the (asynchronous) running of the inner block, which may not be what he wants
0

If you don't want the outer block to retain self, but want the inner block to be able to keep self alive once dispatched, maybe something like this:

typeof(self) __weak weakSelf = self;
self.test = ^{
    typeof(self) strongSelf = weakSelf;
    if (strongSelf) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"%@", strongSelf);
        });
    }
};

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.