iOS - 如何检查 NSOperation 是否在 NSOperationQueue 中?
来自文档:
<块引用>一个操作对象一次最多可以位于一个操作队列中,如果该操作已位于另一个队列中,则此方法会抛出 NSInvalidArgumentException 异常。同样,如果操作当前正在执行或已经完成执行,则此方法会抛出 NSInvalidArgumentException 异常。
那么如何检查是否可以安全地将 NSOperation 添加到队列中?
我知道的唯一方法是添加操作,然后尝试捕获异常(如果该操作已在队列中或之前已执行过)。
From the docs:
An operation object can be in at most one operation queue at a time and this method throws an NSInvalidArgumentException exception if the operation is already in another queue. Similarly, this method throws an NSInvalidArgumentException exception if the operation is currently executing or has already finished executing.
So how do I check if I can safely add an NSOperation into a queue?
The only way I know is add the operation and then try to catch the exception if the operation is already in a queue or executed before.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSOperationQueue
对象有一个名为operations
的属性。如果您有队列的参考,那么很容易检查。
您可以检查 NSArray 操作是否包含您的
NSOperation
,如下所示:或者您可以迭代所有对象:
告诉我这是否是您正在寻找的。
另外,
NSOperation
对象有几个属性可以让你检查它们的状态;例如:isExecuting
、isFinished
、isCancelled
等...NSOperationQueue
objects have a property calledoperations
.If you have a reference to you queues it is easy to check.
You can check if the NSArray of operations contains your
NSOperation
like this:Or you can iterate on all the objects:
Tell me if this is what you are looking for.
Alternatively,
NSOperation
objects have several properties that allow you to check their state; such as:isExecuting
,isFinished
,isCancelled
, etc...当您将 NSOperation 对象添加到 NSOperationQueue 时,NSOperationQueue 会保留该对象,因此 NSOperation 的创建者可以释放它。如果您坚持此策略,NSOperationQueues 将始终是其 NSOperation 对象的唯一所有者,因此您将无法添加 NSOperation > 反对任何其他队列。
如果您在将单个 NSOperation 对象添加到队列后仍想引用它们,则可以使用 NSOperationQueue 的
- (NSArray *)操作方法。
When you add an NSOperation object to a NSOperationQueue, the NSOperationQueue retains the object, so the creator of the NSOperation can release it. If you keep with this strategy, NSOperationQueues will always be the only owner of their NSOperation objects, so you won't be able to add an NSOperation object to any other queue.
If you still want to reference individual NSOperation objects after they've been added to the queue, you can do so using the NSOperationQueue's
- (NSArray *)operations
method.