Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


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];