当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Completion block of an object - retain cycle?

问题描述:

I know...one more question to this topic. But I really don't get it.

My code:

//MyViewController.h

@property (strong, nonatomic) UIPageViewController *pageViewController;

//MyViewController.m

- (void)setViewControllerForIndex:(NSInteger)index {

[self.pageViewController setViewControllers:_myViewControllers[index]

direction:UIPageViewControllerNavigationDirectionForward

animated:animated

completion:^(BOOL finished){

[self updatedViewControllerTo:index]; //this method is doing a lot of stuff

}];

}

Do I have a retain cycle now?

self is being captured in the completion block and self has a strong reference to the pageViewController and so indirectly I have a retain cycle?

Do I have to use the __weak MyViewController *weakSelf statement and use weakSelf in the completion block?

Or: Even when I have a retain cycle does it matter? When the block finishes all the objects in the block will be released and so the retain cycle (or the strong reference to self) will be released, too?

The method updatedViewControllerTo: is doing also UI changes. So the method has to be called. When I'm using weakSelfdo I have to create a strong reference of self in the block? (Referencing to the last code block at http://masteringios.com/blog/2014/03/06/avoid-strong-reference-cycles/).

网友答案:

You do have a retain cycle so please use the weakSelf in your completion block:

Why?

Blocks always retain every object that is passed along with them. You are strong referencing the pageViewontroller that holds a block that is retaining your viewcontroller.

So, these objects are circular referencing eachother so one of them has to have a weak reference. Otherwise, your objects will not be deallocated.

Also you shouldn't worry about the weakSelf reference because: Since you are retaining the pageController in your viewController, it will be 100% certain that when your completionblock gets executed, your "weakSelf" instance is still alive.

网友答案:

The completion block has a strong reference to self. If that completion block is stored away in self then you have a retain cycle. Big problem.

But if that completion block is not stored away, or in some other object, then you just retain self, but you don't have a retain cycle. I cannot know how that block is used. If the method being called just does some things, calls the completion block, and returns, then you are absolutely fine.

网友答案:

Yours self is retained for block. But it isn't problem. Block will be deallocated after invoking and self will be released.

Simple rule: if you release block after invoking you doesn't care about retain cycles in blocks.

分享给朋友:
您可能感兴趣的文章:
随机阅读: