How can I Pause a NSOperation in a NSOperationQueue?

女生的网名这么多〃 提交于 2019-12-03 15:37:44

问题


I need to pause a running NSOperation which was inserted in an NSOperationQueue. Currently I am canceling all operations and restarting them. But this would lead to some kind of duplication in terms of process done. I tried with setSuspended flag of NSOperationQueue. But it's not suspending the operation. Is there any way out?


回答1:


see this: Link

And here from the apple docs:

Suspending and Resuming Queues If you want to issue a temporary halt to the execution of operations, you can suspend the corresponding operation queue using the setSuspended: method.

Suspending a queue does not cause already executing operations to pause in the middle of their tasks. It simply prevents new operations from being scheduled for execution. You might suspend a queue in response to a user request to pause any ongoing work, because the expectation is that the user might eventually want to resume that work.




回答2:


I've not tried this, but I would probably start here:

  • add a isPaused flag to your NSOperation subclass
  • implement a copy/move method for the operation's data
  • if paused, setCancelled: (watch for this change in -main)
  • create a new operation moving the state from paused operation to new operation
  • adjust priority to reorder operation order in queue, if you like
  • add the clone to the queue
  • return from -main if in -main

note that this will just suspend it. if you really want to pause and explicitly resume, you would manually 'new operation` when you want to resume.

now, if you are observing or have special completions, then you will have a few other problems. for simple cases, it seems this approach would seem to work fine.



来源:https://stackoverflow.com/questions/11983625/how-can-i-pause-a-nsoperation-in-a-nsoperationqueue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!