Skip to content
This repository has been archived by the owner on Jun 2, 2018. It is now read-only.

Memory leaks #142

Closed
dev4dev opened this issue May 13, 2013 · 3 comments
Closed

Memory leaks #142

dev4dev opened this issue May 13, 2013 · 3 comments

Comments

@dev4dev
Copy link

dev4dev commented May 13, 2013

Every single usage of something like this

[label whenTapped:^{
    // code here
}];

cause a memory leak like this

screenshot_on_2013-05-13_at_11 17 05

  • used from cocoapods, SDK 6.1, deploy target 5.0
@dev4dev
Copy link
Author

dev4dev commented May 19, 2013

anybody is alive?

@zwaldowski
Copy link
Collaborator

This behavior is by design; it isn't an actual leak in BlocksKit. Blocks retain the objects referenced inside the block's scope, so this will cause a retain cycle if the block references something that retains the view. For example, if you add a block to a view from within a view controller's -viewDidLoad, then the block retains the view controller which the retains the view which retains the block, and so on forever and ever. Clang can detect this kind of thing itself if it's a simple case (a block property on the class is capturing self) and warn you about it, even.

To fix this yourself, you'll want to __weak reference the object that causes the retain cycle. Depending on how the block gets called, you also might want to __strong reference the weak reference inside the block. That'd look something like this, using our previous UIViewController example:

- (void)viewDidLoad {
    __weak MyViewController *weakSelf = self;
    [self.tappableView whenTapped:^{
        __strong MyViewController *strongSelf = weakSelf;
        [strongSelf doSomething];
    }];
}

You could also use libextobjc's strongify and weakify macros to do it, same type of thing but prettier.

Alternatively, we could add a method to BlocksKit to remove all view blocks and forcibly break the cycles, but it's better in my humble opinion if you know why it's happening yourself. ;-)

@dev4dev
Copy link
Author

dev4dev commented May 20, 2013

Thanks for answer.
I know about retain cycles. And it happens even if code block is empty.
And I was surprised, because using addHandler for UIButton doesn't have the same behavior and everything is clear.
Ok, never mind =)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants