3

通常,一旦mainan 的方法NSOperation完成,操作就会被标记为完成并从队列中删除。但是,我的操作进行网络调用,我想处理重试。NSOperationNSOperationQueue我明确表示可以删除之前,我如何保留它?

4

1 回答 1

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];
    }
}

编写完成操作的代码...

- (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”方法。

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

于 2012-11-30T16:01:24.287 回答