我有一个要同时运行的 NSOperation 子类。

我的理解是,要使并发操作起作用:

  • 我需要定义 isConcurrent 来返回 YES
  • 我需要定义 start 方法
  • 完成后,我需要为 isExecutingisFinished 发送 KVO 通知。
  • @synthesizeisExecuting 的值发生变化时,使用 isFinished 将自动发送适当的 KVO 通知。

  • 尽管如此,我已经确认我的队列永远不会移动到下一个项目。

    这是我的代码的主要内容:
    @interface MyOperation()
    
    @property (readwrite) BOOL isExecuting;
    @property (readwrite) BOOL isFinished;
    
    @end
    
    @implementation MyOperation
    
    - (void)start
    {
        @autoreleasepool {
            self.isExecuting = YES;
            self.HTTPOperation = [[AFHTTPRequestOperation alloc] initWithRequest: URLRequest];
    
            _HTTPOperation.completionBlock = [^{
                [self completed];
    
                self.isExecuting = NO;
                self.isFinished = YES;
            } copy];
    
            [_HTTPOperation start];
        }
    }
    
    - (BOOL)isConcurrent
    {
        return YES;
    }
    
    - (void)completed
    {
    }
    
    @end
    

    我错过了什么?

    (这是在 iPhone 上,但我无法想象这很重要。)

    最佳答案

    看起来 @synthesize 发送的任何 KVO 通知都不足以让 NSOperationQueue 继续前进。

    手动发送通知可解决问题:

    - (void)start
    {
        @autoreleasepool {
            [self willChangeValueForKey:@"isExecuting"];
            self.isExecuting = YES;
            [self didChangeValueForKey:@"isExecuting"];
    
            NSURLRequest *URLRequest = [self buildRequest];
            if (!URLRequest) {
                [self willChangeValueForKey:@"isFinished"];
                [self willChangeValueForKey:@"isExecuting"];
                _isExecuting = NO;
                _isFinished = YES;
                [self didChangeValueForKey:@"isExecuting"];
                [self didChangeValueForKey:@"isFinished"];
                return;
            }
    
            self.HTTPOperation = [[AFHTTPRequestOperation alloc] initWithRequest: URLRequest];
    
            _HTTPOperation.completionBlock = [^{
                [self completed];
    
                [self willChangeValueForKey:@"isFinished"];
                [self willChangeValueForKey:@"isExecuting"];
                _isExecuting = NO;
                _isFinished = YES;
                [self didChangeValueForKey:@"isExecuting"];
                [self didChangeValueForKey:@"isFinished"];
            } copy];
    
            [_HTTPOperation start];
        }
    }
    

    也可以看看:
  • Why does NSOperation disable automatic key-value observing?
  • 关于cocoa-touch - 为什么我的 NSOperation 子类永远不会完成?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10422883/

    10-12 00:15