NSBlockOperation leaks ARC

971 views Asked by At

I'm having troubles referring to the ´NSBlockOperation´ inside the block itself. I need to check if the operation was cancelled and it seems that any access to the ´searchOperation´ just leaks when running in an ARC-enabled project.

This code, which basically does nothing, shows the leak in an ARC enabled project while works fine in a non-ARC one.

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.searchQueue = [[NSOperationQueue alloc] init];
    self.searchQueue.maxConcurrentOperationCount = 1;

    __block NSBlockOperation *searchOperation = [NSBlockOperation blockOperationWithBlock:^{
        if (searchOperation.isCancelled) return;
    }];

    [self.searchQueue addOperation:searchOperation];
}

Thanks.

1

There are 1 answers

0
Jonathan Cichon On BEST ANSWER

you have declare searchOperation as __weak to avoid retain cycle:

__weak NSBlockOperation *searchOperation;
NSBlockOperation *tmp = [NSBlockOperation blockOperationWithBlock:^{
    if (searchOperation.isCancelled) return;
}];
searchOperation = tmp;

Another possible solution: set searchOperation to nil inside the block after you used it.