即使在完成后将NSOperation保持在队列中

时间:2012-11-30 14:42:29

标签: ios cocoa nsoperation

通常,当main的{​​{1}}方法完成后,操作将标记为已完成,并从队列中删除。但是,我的操作会进行网络呼叫,我想处理重试。如果明确说明删除它,我如何在NSOperation中保留NSOperation

1 个答案:

答案 0 :(得分:4)

我无法找到我在当前项目中所做工作的原始来源。

我已经将NSOperation子类化并执行此操作......

在.m ...

中添加私有属性
@property (nonatomic) BOOL executing;
@property (nonatomic) BOOL finished;
@property (nonatomic) BOOL completed;

初始化操作......

- (id)init
{
    self = [super init];
    if (self) {
        _executing = NO;
        _finished = NO;
        _completed = NO;
    }
    return self;
}

添加函数以返回属性...

- (BOOL)isExecuting { return self.executing; }
- (BOOL)isFinished { return self.finished; }
- (BOOL)isCompleted { return self.completed; }
- (BOOL)isConcurrent { return YES; }

在“开始”功能中(这是operationQueue调用的位...

- (void)start
{
    if ([self isCancelled]) {
        [self willChangeValueForKey:@"isFinished"];
        self.finished = YES;
        [self didChangeValueForKey:@"isFinished"];
        return;
    }

    // If the operation is not canceled, begin executing the task.
    [self willChangeValueForKey:@"isExecuting"];
    self.executing = YES;
    [self didChangeValueForKey:@"isExecuting"];

    [NSThread detachNewThreadSelector:@selector(main) toTarget:self withObject:nil];
}

然后在主要的工作代码...

- (void)main
{
    @try {
        //this is where your loop would go with your counter and stuff
        //when you want the operationQueue to be notified that the work
        //is done just call...
        [self completeOperation];
    }
    @catch (NSException *exception) {
        NSLog(@"Exception! %@", exception);
        [self completeOperation];
    }
}

编写completeOperation的代码......

- (void)completeOperation {
    [self willChangeValueForKey:@"isFinished"];
    [self willChangeValueForKey:@"isExecuting"];

    self.executing = NO;
    self.finished = YES;

    [self didChangeValueForKey:@"isExecuting"];
    [self didChangeValueForKey:@"isFinished"];
}

就是这样。

只要你有这些,那么操作就可以了。

您可以根据需要添加任意数量的其他功能和属性。

事实上,我实际上已经将这个类子类化了,因为我有一个函数可以完成不同类型对象的所有工作(它是一个上传的东西)。我已经定义了一个函数......

- (void)uploadData
{
    //subclass this method.
}

然后我在子类中拥有的是一个自定义的“uploadData”方法。

我发现这非常有用,因为它可以让您精确控制何时完成操作......