Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top