NSOperation 取消:NSInitationOperation 还是 NSOperation 子类?

发布于 2024-10-23 18:21:01 字数 707 浏览 2 评论 0原文

我有一个相当简单但昂贵的任务,我需要在后台运行,这是标准的 NSOperation 情况。我还需要确保操作支持取消并适当停止。考虑到这个要求,哪个是更好的方法:只是将昂贵的方法调用包装在 NSInvocableOperation 中,还是从头开始编写 NSOperation 子类?

到目前为止,这是我的想法。 NSIncationOperations 是我的第一选择,也是我过去使用过的,因为任务非常简单,我不想用所有 NSOperation 样板代码编写整个类来执行它。现在让我犹豫的是,似乎没有一种方法可以让在 NSInitationOperation 中执行的方法来检查取消,而不会在我的脑海中触发黑客警报。有关上述黑客行为的一些示例,请参阅此问题。我已经尝试过了,它们确实有效,但也感觉很恶心。

正如前面提到的,编写一个 NSOperation 子类对于执行这个简单的任务来说似乎有点矫枉过正,但毫无疑问,检查取消比我遇到的任何 NSInitationOperation 都更优雅。

那么,对于那些拥有更多 NSOperations 的人来说,您使用过哪些操作最成功呢?我可能错过了使用 NSInitationOperations 的一个很好的取消解决方案吗?如果没有某种形式的取消支持,NSInitationOperations 有用的情况数量就会急剧下降。

I have a fairly simple, though expensive, task that I need to run in the background, which is the standard NSOperation situation. I also need to make sure the operation supports cancellation, and stops appropriately. Given that requirement, which is the better approach: Just wrapping up the expensive method call in an NSInvocationOperation, or writing an NSOperation subclass from scratch?

Here's my thinking so far. NSInvocationOperations are my first choice, and are what I've used in the past, because the task is so simple that I don't want to write a whole class with all the NSOperation boilerplate code just to execute it. What now makes me hesitate is the fact that there doesn't really seem to be a way for an method executed in an NSInvocationOperation to check for cancellation that doesn't set off the hackery alarm in my head. See this question for some examples of said hackery. I've tried them, and they do work, they just also feel icky.

Writing an NSOperation subclass, as mentioned before, seems like overkill to perform the simple task, but there is no doubt that checking for cancellation is more elegant than anything I've come across for NSInvocationOperation.

So, for those who have more NSOperations under their belt, which have you used to the most successful end? Is there a nice cancellation solution using NSInvocationOperations that I may have missed? Without some sort of support for cancellation, the number of situations where NSInvocationOperations are useful just went off a cliff.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时光礼记 2024-10-30 18:21:01

我相信,子类化 NSOperation 是执行此操作的唯一优雅方法。

当我将现有代码重构为多线程时,我倾向于只使用 NSInitationOperations,那么它是一个方便的快捷方式。

Subclassing NSOperation is the only elegant way to do this, I believe.

I tend only to use NSInvocationOperations when I'm refactoring existing code to be multithreaded, then it's a handy shortcut.

稳稳的幸福 2024-10-30 18:21:01

只是 NSOperation 的子类。 (需要更多字符)

just subclass NSOperation. (more characters required)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文