NSOperationQueue out of range exception
I have a strange error which pop up recently. The NSOperationQueue says it has 1 object 开发者_Python百科in it however I cannot access the NSOperation object inside it.
if ([[queue operations] count] > 0)
op = [queue.operations objectAtIndex:0];
But for some reason it ends up in the following exception: index 0 beyond bounds for empty array'
I understand the error message however I am surprised since I was checking the queue count before asking for the object itself.
Any ideas please?
Remember that operations are able to run on separate threads and usually are. An NSOperationQueue
actually has its own method for getting the count called operationCount
and provides this word of caution:
The value returned by this method reflects the instantaneous number of objects in the queue and changes as operations are completed. As a result, by the time you use the returned value, the actual number of operations may be different. You should therefore use this value only for approximate guidance and should not rely on it for object enumerations or other precise calculations.
What you are running into is probably a concurrency issue. One thing to consider is to copy the operations array.
NSArray *ops = [queue.operations copy];
if ([ops count] > 0)
{
op = [ops objectAtIndex:0];
//You can check if it has finished using [op isFinished];
//and do what you need to do here
}
[ops release];
Update:
Here is an example of why you may see this happening very often
//Set up and start an NSOperation
...
//Here your call to operations probably put some sort of lock
//around operations to retrieve them but your operation also
//finished and is waiting for your lock to complete to remove
//the operation. The operations call probably returns a copy.
if([[que operations] count] > 0)
{
//Now the operation queue can access its operations and remove
//the item with the lock released (it can actually access as early
//as before the call and count)
//Uh oh now there are 0 operations
op = [queue.operations objectAtIndex:0];
}
the operation may have completed between the two calls
精彩评论