r/ObjectiveC • • Nov 03 '19

Avoiding a retain cycle.

This is my code for checking the internet connection on an iOS device and then implementing the function which calls the API. However, I am getting an error when I call the function (self getURL:page), saying that

Capturing 'self' strongly in this block is likely to lead to a retain cycle

What can I do to get around that?

Code:

- (void)testInternetConnection
{
    isInternetReachable = [Reachability reachabilityWithHostname:@"www.google.com"];

    isInternetReachable.reachableBlock = ^(Reachability*reach)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Yayyy, we have the interwebs!");
            [self getURL:page];
        });
    };

    isInternetReachable.unreachableBlock = ^(Reachability*reach)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Someone broke the internet :(");
        });
    };
    [isInternetReachable startNotifier];
}
3 Upvotes

3 comments sorted by

View all comments

Show parent comment

6

u/sneeden Nov 04 '19

Here is a formatted snippet:

__weak typeof(self) welf = self;
[self saveThingInContext:context completion:^(NSArray<NSNumber *> *serverIds) {
    welf.serverIds = [serverIds copy];
}];