0

I have the following code (in a non-ARC project):

- (void)loadWithCompleteBlock:(void (^)(void))complete
{    
    ...
    complete = [complete copy];
    ...            
    [[NSOperationQueue mainQueue] addObserver:self forKeyPath:@"operationCount" options:0 context:complete];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *) context
{
    void (^complete)(void) = context;
    [self performSelectorInBackground:@selector(loadFilesWithCompleteBlock:) withObject:complete];
    [complete release];
}

The static analyzer gives the warning Potential leak of an object stored into 'complete'

I tired to add NS_RELEASES_ARGUMENT or CF_RELEASES_ARGUMENT to the context parameter, but nothing works.

Any ideas?

Alexander
  • 1,495
  • 2
  • 19
  • 24

1 Answers1

2

Passing an object through a void* and release it in a callback method is something the analyzer cannot understand. You could just silence the analyzer for these cases.

But in this case the code is broken anyway and should be refactored. You cannot use KVO's context to pass an object to the callback: You need the context to identify the observation. See for example Dave Dribin's description of how to do KVO properly.

Can't you just set the block as a completion block to the operation you add?

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • Why is my code broken? It works... How can I silence the analyzer? I have multiple operations on the queue and want to know, when all are completed. But I don't want to block the current thread with something like ```waitUntilAllOperationsAreFinished```. – Alexander Sep 25 '13 at 11:23
  • @Alexander "It works" is a very bad excuse for bad code. As I said, the way you misuse KVO's context leading to trouble and you should adopt another pattern. You could set the block as an instance variable on the class that owns the queue, for example. – Nikolai Ruhe Sep 25 '13 at 12:44
  • Here is a good explanation what context is intended for: http://stackoverflow.com/a/11917449/393863 – Alexander Oct 16 '13 at 11:31