NSOperationQueue超出范围异常

Ted*_*ddy 1 iphone

我最近弹出一个奇怪的错误.NSOperationQueue说它有1个对象但是我无法访问其中的NSOperation对象.

    if ([[queue operations] count] > 0)
    op = [queue.operations objectAtIndex:0];
Run Code Online (Sandbox Code Playgroud)

但由于某种原因,它最终会出现以下异常:索引0超出空数组的边界'

我理解错误信息然而我很惊讶,因为我在询问对象本身之前检查队列计数.

有什么想法吗?

Joe*_*Joe 5

请记住,操作可以在不同的线程上运行,通常是.一个NSOperationQueue真正有自己的用于获取所谓的计数方法operationCount,并提供谨慎的这句话:

此方法返回的值反映队列中对象的瞬时数量,并在操作完成时进行更改.因此,在您使用返回值时,实际操作数可能会有所不同.因此,您应该仅将此值用于近似指导,并且不应将其用于对象枚举或其他精确计算.

您遇到的可能是并发问题.要考虑的一件事是复制操作数组.

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];
Run Code Online (Sandbox Code Playgroud)

更新:

这是一个为什么你可能经常看到这种情况的例子

//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];

}
Run Code Online (Sandbox Code Playgroud)