记住操作都能够在单独的线程运行,通常之间完成。一个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];
更新:
这就是为什么你会看到这种情况出现往往一个例子
//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];
}
来源
2011-06-30 16:34:27
Joe
你的意思是检查的次数和分配变量之间存在如此高的手术完成的机会? 这种情况很奇怪,因为op =赋值是毫无意义的,根本无法使用。 – Teddy
是不是并发性很好?这就是复制操作的原因,如果你真的想用第一个操作做一些操作,像我的例子那样复制操作,然后你可以安全地使用'op'。如果你关心它是否完成,只需调用'isFinished'方法即可。 – Joe
不错。我一直在我的代码中使用一些苹果示例,但似乎应该注意这个“复制”的东西。与此同时,我没有使用op =语句解决了这个问题,因为没有真正的需要。再次感谢乔。 – Teddy