我创建了一个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];