Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Nic Huang
Nic Huang
Courses Plus Student 10,573 Points

Block and self cause retain cycle

I was told block would cause retain cycle when you use self in block like this:

 self.onCompleteBlock = ^{
    [self doSomething];
[[SSDHTTPClient sharedInstance] login:parameters completion:^(BOOL success, NSURLSessionDataTask *task, id responseObject) {

        if (success) {

            NSString *string = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSDictionary *dict = [self splitString: string];
                self.userID = dict[@"userID"];
                self.subscriberID = dict[@"subscriberID"];
                [self writeUserIDIntoUserDefault:self.userID withSubscriberID:self.subscriberID];

But I want to know if I use block this way, does it cause retain cycle too? Because when I profiled this code in instrument, it doesn't show any leak. And in Xcode, the viewController's dealloc is also properly get called.

1 Answer

Thomas Nilsen
Thomas Nilsen
14,957 Points

It's not correct to say it will cause a retain cycle, but it CAN. You can avoid it by doing something like this:

__typeof(self) __weak weakSelf = self;
 self.onCompleteBlock = ^{
    [weakSelf doSomething];