ios - 使用依赖项创建FIFO NSOperationQueue

标签 ios nsoperation nsoperationqueue fifo

我创建了一个NSOperationQueue子类,将maxConcurrentOperations设置为1,并将addOperation方法重写为以下内容:

-(void)addOperation:(NSOperation *)op
{
    // If there are already operations on the queue, add the last operation as a dependency to the delay. Ensures FIFO.
    if ([[self operations] count] > 0) [op addDependency:[self.operations lastObject]];
    [super addOperation:op];
}

这是在这里的某个地方建议的(我手边没有链接)。问题是我偶尔会在这里崩溃:

*由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“* -[__ NSArrayM insertObject:atIndex:]:对象不能为零”

在崩溃时,[[self operation] count] == 0,因此大概在检查[[self actions] count]> 0和addDependency调用之间的纳秒内,队列上的最后一个操作完成了执行,变为nil 。

我的问题是,我该如何解决?

最佳答案

为避免此NSInvalidArgumentException问题,只需在此方法的持续时间内建立对lastObject的本地引用,然后进行测试:

NSOperation *lastOperation = [self.operations lastObject];
if (lastOperation) [op addDependency:lastOperation];

关于ios - 使用依赖项创建FIFO NSOperationQueue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33263208/

相关文章:

ios - pod update --verbose & pod install --verbose 未完成,挂起

objective-c - waitUntilAllOperationsAreFinished(NSOperationQueue)后面写了什么代码?

ios - CGContext 绘制旋转的矩形

ios - Xcode 4 - 将 iOS 开发人员库引用添加到 Organizer - 文档

ios - 如何在 swift 4 中执行两个并发 API 调用

cocoa - 使用 NSOperation main() 和 start() 方法中的哪一个

cocoa - 将 NSOperation 的自定义子类标记为已终止?

ios - NSOperation 取消和 NSOperationQueue

ios - 当 viewWillDisappear 时 NSOperationQueue cancelAllOperations 不起作用

iphone - 如何从外部框架加载资源