2

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.

Tomas Camin
  • 9,996
  • 2
  • 43
  • 62

1 Answers1

5

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.

Jonathan Cichon
  • 4,396
  • 16
  • 19