Making a dependency on the last object in an NSOperationQueue, for FIFO behaviour

Hi there

I've created a NSOperationQueue subclass, and have overridden the addDependency method to be the following:


-(void)addOperation:(NSOperation *)op 
{
if ([[self operations] count] > 0) [op addDependency:[self.operations lastObject]]; 
[super addOperation:op]; 
}


This approach was suggested in several places on Stack Overflow. The trouble is that I occasionally get a crash here:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[__NSArrayM insertObject:atIndex:]: object cannot be nil'

At crash time, [[self operations] count] == 0, so presumably in the nanoseconds between the check [[self operations] count] > 0, and the addDependency call, the last operation on the queue finished executing, and became nil.

My question is, how do I work around this? Or am I looking at a bug?

Replies

Just call [self operations] (a.k.a. self.operations) once, not twice. Store the pointer in a local variable and use that in the two places you currently query the property. The method returns a snapshot array. It is not the internal array. So, its contents won't change spontaneously.


That said, this subclass just seems to be implementing a serial queue. Why not simply set maxConcurrentOperationCount to 1?