首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用NSOperationQueue作为后进先出堆栈?

使用NSOperationQueue作为后进先出堆栈?
EN

Stack Overflow用户
提问于 2012-04-10 03:24:12
回答 6查看 5K关注 0票数 8

我需要做一系列的url调用(获取WMS磁贴)。我想使用后进先出堆栈,所以最新的url调用是最重要的。我想现在在屏幕上显示磁贴,而不是5秒前平移后显示在屏幕上的磁贴。

我可以从NSMutableArray创建自己的堆栈,但我想知道NSOperationQueue是否可以用作后进先出堆栈?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2012-04-10 03:36:13

遗憾的是,顾名思义,我认为NSOperationQueue只能用作队列,而不能用作堆栈。要避免进行一大堆手动编组任务,最简单的方法可能是将队列视为不可变的,并通过复制使其发生变化。例如。

代码语言:javascript
复制
- (NSOperationQueue *)addOperation:(NSOperation *)operation toHeadOfQueue:(NSOperationQueue *)queue
{
    // suspending a queue prevents it from issuing new operations; it doesn't
    // pause any already ongoing operations. So we do this to prevent a race
    // condition as we copy operations from the queue
    queue.suspended = YES;

    // create a new queue
    NSOperationQueue *mutatedQueue = [[NSOperationQueue alloc] init];

    // add the new operation at the head
    [mutatedQueue addOperation:operation];

    // copy in all the preexisting operations that haven't yet started
    for(NSOperation *operation in [queue operations])
    {
        if(!operation.isExecuting)
            [mutatedQueue addOperation:operation];
    }

    // the caller should now ensure the original queue is disposed of...
}

/* ... elsewhere ... */

NSOperationQueue *newQueue = [self addOperation:newOperation toHeadOfQueue:operationQueue];
[operationQueue release];
operationQueue = newQueue;

目前看来,释放仍在工作的队列(就像旧的操作队列一样)并不会导致它取消所有操作,但这并不是记录在案的行为,因此可能不值得信任。如果您想要真正安全,键值观察旧队列上的operationCount属性,并在它变为零时释放它。

票数 3
EN

Stack Overflow用户

发布于 2012-04-10 13:35:17

您可以使用-[NSOperation setQueuePriority:]设置操作队列中操作的优先级。每次添加操作时,您都必须重新调整现有操作的优先级,但您可以实现您正在寻找的东西。你基本上会降级所有旧的,并给予最新的最高优先级。

票数 5
EN

Stack Overflow用户

发布于 2012-10-04 04:31:48

我不确定您是否还在寻找解决方案,但是我已经被同样的问题困扰了一段时间,所以我继续在这里实现了一个操作堆栈:https://github.com/cbrauchli/CBOperationStack。我已经使用它进行了几百次下载操作,并且运行良好。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10078569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档