2015-10-21 38 views
1

我创建了一个NSOperationQueue子类,设置maxConcurrentOperations为1,并且已经覆盖了addOperation方法如下所示:使用依赖创建FIFO NSOperationQueue

-(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 operations] count] == 0,所以大概在check [[self operations] count]> 0和addDependency调用之间的纳秒内,队列上的最后一个操作完成,并且成为零。

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

+1

你试过包'addDependency'在try-catch块?然后你可以通过不添加依赖来处理异常。 – joern

+0

其实不行!这是一个美妙的主意......自从我开始编写Obj-C以来,我实际上已经忘记了try-catch的存在。 –

+0

我使用try catch方法添加了一个答案。 – joern

回答

2

为了避免这个问题NSInvalidArgumentException,只是建立这种方法的持续时间的本地参考lastObject,然后测试:

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

如果您不能修复崩溃,你至少可以包裹在一个try-catch块的addDependency

-(void)addOperation:(NSOperation *)op { 
    @try { 
     if ([[self operations] count] > 0) [op addDependency:[self.operations lastObject]]; 
    } 
    @catch (NSException *exception) { 
     // ignore  
    } 
    @finally { 
     [super addOperation:op]; 
    } 
} 

这至少避免了撞车。